最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Forcing input value (Angular) - Stack Overflow

programmeradmin5浏览0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 6

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./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 [(

发布评论

评论列表(0)

  1. 暂无评论