I'm trying to manually restrict user from enter a value in input more than a certain value. I'm using Angular 9 and ngModel on the input.
As you can see in the below code, on ngModelChange, if the input value for age is larger than 27, I'm setting it to 27.
If the user inputs a bigger number like 144, it displays 27 in the input box as soon as the user types the last 4. But for numbers that have 27 as the prefix, e.g. 271, 2700, etc., the value displayed in input box is not changed. Does anyone know why and is there a way to have it display correctly?
Please note that the variable age is set correctly to 27 for all larger numbers. Just that the input box display does not change for numbers that have 27 as the prefix.
Here is the Codepen link: https://codepen.io/baggasumit/pen/MWVgaqZ
@Component({
selector: 'my-app',
template: `
<h1>ngModel Example</h1>
<label>Age </label>
<input type="number" max="27" [ngModel]="age" (ngModelChange)=onAgeChange($event) />
<br>
<br>
<div>Age is set to {{age}}</div>
`
})
class AppComponent {
public age;
public onAgeChange(newAge) {
if (newAge > 27) {
this.age = 27;
} else {
this.age = newAge;
}
console.log(this.age);
}
}