I would like to bind the input value to the model using getter and seters. This way I can prevent and / or manipulate the input value while writing inside it.
For example, I want the numbers placed inside the input field to be blocked. So, if the record "abc" is all right, then if I start writing the number, nothing should happen (with the model and with the input value). The problem is that with the following code, I can write something inside the input field (but the model is correct). This means that the value of the input field does not represent my model.
NOTE. The reason underlying this question is because I want to use my models to validate forms, preventing, for example, specific characters. I would not want to use reactive forms like . I want to keep my checks inside my models not components. Also note that in a real scenario, I will have a UserModel class with an internal name and other fields with their checks.
@Component({
selector: 'my-app',
template: `
<div>
<h2><input type="text" [(ngModel)]="name"> {{name}}</h2>
</div>
`,
})
export class App {
_name:string = 'ss';
constructor() {
}
get name() {
return this._name;
}
set name() {
if ((new RegExp(/^[a-zA-Z]*$/).test(val))) {
this._name = val;
}
}
}
source
share