Home > Blockchain >  Forcing input value (Angular)
Forcing input value (Angular)

Time:07-26

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 handred. 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 a 100, but after that i doesn't.

My understanding of it is that the DOM doesn't update when there no value updates.

I can solve this problem using other methods using @ViewChild for example, but I am more intersted in knowing how this works and how angular handles this specific use case.

Thanks!

CodePudding user response:

The 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.com/edit/angular-ivy-upykps?file=src/app/app.component.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 accomplished with the banana-in-a-box [(

  • Related