I have the following input
<input type="number" [ngModel]="inputValue" (ngModelChange)="handleChange($event)"/>
And I am trying to force the input to stay less or equal to 100. using the method handleChange
export class AppComponent {
inputValue: number = 0;
handleChange($event: any) {
if ($event > 100) {
this.inputValue = 100;
}
}
}
And it only works the first time I enter the first input that is higher than 100, but after that it doesn't.
My understanding of it is that the DOM doesn't update when there are no value updates.
I can solve this problem using other methods like @ViewChild for example, but I am more interested in knowing how this works and how angular handles this specific use case.
Thanks!
I have the following input
<input type="number" [ngModel]="inputValue" (ngModelChange)="handleChange($event)"/>
And I am trying to force the input to stay less or equal to 100. using the method handleChange
export class AppComponent {
inputValue: number = 0;
handleChange($event: any) {
if ($event > 100) {
this.inputValue = 100;
}
}
}
And it only works the first time I enter the first input that is higher than 100, but after that it doesn't.
My understanding of it is that the DOM doesn't update when there are no value updates.
I can solve this problem using other methods like @ViewChild for example, but I am more interested in knowing how this works and how angular handles this specific use case.
Thanks!
Share Improve this question edited Mar 30, 2024 at 18:40 Josh Correia 4,3643 gold badges42 silver badges63 bronze badges asked Jul 25, 2022 at 18:34 N. younesN. younes 1015 bronze badges4 Answers
Reset to default 6The solution is to introduce two-way binding, so your property and the html value are synchronized. You also need to force change detection before setting the property to 100.
Stackblitz: https://stackblitz./edit/angular-ivy-upykps?file=src/app/app.ponent.ts
Both of these steps are necessary for the change detector to detect that the property has changed every time, only then will it update the html value with your property value.
Two way binding is acplished with the banana-in-a-box [(