As a newcomer to Angular, I am struggling with converting types between form field values (which are always strings) and typed model properties.
In the following component, my goal is to double a number inputted by the user. The result will be displayed in the console.
import { Component } from '@angular/core';
@Component({
selector: 'app-model-view-conversion',
template: `
<input [(ngModel)]="aNumber" (keyup)="double()" />
`
})
export class ModelViewConversionComponent {
aNumber: number;
double() {
console.log(this.aNumber + this.aNumber); // For example, if you input 7, the output will be 77
}
}
It's important to note that TypeScript and Angular do not automatically convert between strings and numbers. Therefore, concatenation occurs instead of addition. This demonstration serves solely for educational purposes.
I'm wondering where and how should this conversion take place?
One approach I have considered involves the following:
import { Component, DoCheck } from '@angular/core';
@Component({
selector: 'app-model-view-conversion',
template: `
<input [(ngModel)]="viewNumber" (keyup)="double()" />
`
})
export class ModelViewConversionComponent implements DoCheck {
viewNumber: string;
modelNumber: number;
ngDoCheck() {
this.modelNumber = parseInt(this.viewNumber);
}
double() {
console.log(this.modelNumber + this.modelNumber); // If you input 7, the output will now be 14
}
}
While this solution works, it still requires manual synchronization between the model and the view. Is there a more efficient way, such as using converters similar to those found in JavaServer Faces?
Another idea revolves around implementing getters/setters in the model:
import { Component } from '@angular/core';
@Component({
selector: 'app-model-view-conversion',
template: `
<input [(ngModel)]="aNumber" (keyup)="double()" />
`
})
export class ModelViewConversionComponent {
num: number;
set aNumber(numAsString) {
this.num = parseInt(<any>numAsString);
};
get aNumber() {
return this.num;
}
double() {
console.log(this.num + this.num);
}
}
This also feels somewhat cumbersome and excessively verbose to me. Additionally, TypeScript necessitates the use of <any>
casting for smoother compilation.
If anyone could offer guidance on a better approach, I would greatly appreciate it. Thank you.