【问题标题】:NgModelChange on input number not updating the view输入编号上的 NgModelChange 不更新视图
【发布时间】:2020-08-07 09:13:26
【问题描述】:

我目前正在尝试创建一个输入数字,以防止用户输入高于 @Input() maxValue 的数字,我是这样实现的:

HTML:

<input
    class="number-selector-input"
    type="number"
    [(ngModel)]="value"
    (ngModelChange)="checkValue($event)"
/>

打字稿:

public checkValue(value) {
  if (value > this.maxValue) { 
    this.value = this.maxValue;
  }
  if (value < this.minValue) { 
    this.value = this.minValue;
  }
}

它工作得很好,但仍然有一个我无法理解的问题。我有一个 maxValue 等于 100,当我输入 150 或 200 时,它会自动更改为 100,但当我输入 1000 时,输入数字不会更新。

当我尝试在控制台或直接在 HTML 中显示该值时,模型正确地等于 100。您有什么想法可以帮助我理解这一点吗?

【问题讨论】:

    标签: angular input angular-ngmodel


    【解决方案1】:

    说实话,这是个奇怪的错误,我进行了测试,它表现出相同的行为。

    但是,您可以通过添加一个指令来规避这一点,这在 imo 中也更加简洁,因为它不会用函数使您的组件混乱

    指令:

    import { Directive, Input, ElementRef, HostListener } from '@angular/core';
    
    @Directive({
      selector: '[minMax]'
    })
    export class MinMaxDirective {
    
      @Input()
      public min: number;
    
      @Input()
      public max: number;
    
      constructor(private ref: ElementRef) { }
    
        @HostListener('input', [ '$event' ])
      public onInput(a_Event: InputEvent): void {
        let val = parseInt(this.ref.nativeElement.value);
        if(this.max !== null && this.max !== undefined  && val >= this.max)
          this.ref.nativeElement.value = this.max.toString();
        else if (this.min !== null && this.min !== undefined  && val <= this.min)
          this.ref.nativeElement.value = this.min.toString();
      }
    
    }
    

    用法:

    <input
        [(ngModel)]="value"
        [min]="minValue"
        [max]="maxValue"
        minMax
        class="number-selector-input"
        type="number"/>
    

    演示:https://stackblitz.com/edit/angular-input-min-max-directive

    【讨论】:

    • 哦,谢谢您的回答,我找到了另一种解决方案,但您的似乎更好!
    【解决方案2】:

    你可以试试这个

    <input
            class="number-selector-input"
            type="number"
            [(ngModel)]="value"
            (ngModelChange)="checkValue($event)"
        />
        
        public checkValue(value) {
          if (+value > this.maxValue) { 
            this.value = this.maxValue;
          }
          if (value < this.minValue) { 
            this.value = this.minValue;
          }
        }
    

    【讨论】:

    • 感谢您的快速响应,它也不起作用
    【解决方案3】:

    我设法通过使用 (keyup) 而不是 (ngModelChange) 来解决我的问题:

    (ngModelChange)="checkValue($event)" --> (keyup)="checkValue($event)"
    

    而 checkValue(value) 方法变成了:

    public checkValue(event) {
      if (event.target.value > this.maxValue) {
        this.value = this.maxValue;
      }
      if (event.target.value < this.minValue) {
        this.value = this.minValue;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-04
      • 2019-04-24
      • 2020-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      相关资源
      最近更新 更多