当值没有改变时如何强制 ngModel 更新?

How to force ngModel update when value did not change?

我想将数字输入限制在 0-100 范围内,但在输入时,而不是在验证期间。我正在使用 ngModel 绑定值并发出更改事件:

<input [ngModel]="value" (ngModelChange)="validate($event)" />

然后检查值是否超出给定限制:

public validate(value) {
    if (value > 100)
        this.value = 100;
    if (value < 0)
        this.value = 0;
}

而且这个部分有效。但是,如果我说尝试输入 150 并且值将切换为 100,那么我可以输入任何超过 100 的值,因为模型值保持为 100,因此输入值不会更新。有什么方法可以手动强制更新吗?

编辑:我在这里错过了很重要的一点。这种行为似乎只发生在输入 type=number 时。文本输入不会超过 100。我的解决方法是 Faisal 建议使用带有 preventDefault 的按键事件,如下所示:

public keyPress(event) {
    let inputChar: number = +String.fromCharCode(event.charCode);
    if (this.value + inputChar > 100 || this.value + inputChar < 0) {
        // Exceeded limits, prevent input
        event.preventDefault();
    }
}

您可以添加其他部分以反映更改。

public validate(value){
    if(value>100)
        this.value=100;
    else
        this.value = value    
}

另一种方式 .. 据我所知是使用 NgZone(相当于 AngularJs $scope.$apply()).. 比如:

constructor(private _ngZone:NgZone){

}


public validate(value){
    if(value>100)
        this.value=100;
    if(value<0)
        this.value=0;

this._ngzone.run(()=>{
 this.value=(value>100) ? 100  ? (value<0) ? 0 : 0;
});

}

使用正则表达式限制用户输入。

Here is the html code for your input:

<input [(ngModel)]="value" 
       (keypress)="keyPress($event)"
       (ngModelChange)="validate($event)"  
        maxlength=3 />

.. and typescript code:

keyPress(event: any) {
    const pattern = /[0-9]/;
    let inputChar = String.fromCharCode(event.charCode);

    if (!pattern.test(inputChar)) {
        // invalid character, prevent input
        event.preventDefault();
    }
}

validate(value:number) {
    if(value>100) {
        this.value=100;
    }
}

这是一个正在工作的插件:Plunker DEMO

我遇到了同样的问题,但找到了我更喜欢的不同解决方案。正如您所说,问题在于模型中的值在您的函数之前和之后是相同的。 我所做的是在更改值之前调用 Angular 的更改检测,以便它注册更改。为此,请使用 ChangeDetectorRef class 并调用其 detectChanges 方法。

因此,您的函数变为:

public validate(value) {
    this.changeDetector.detectChanges();
    if (value > 100)
        this.value = 100;
    if (value < 0)
        this.value = 0;
}

而且效果很好。希望对你有帮助。

我遇到了类似的问题。当结果等于之前的输入值时,我的输入没有更新。

我这样使用 @ViewChild : 在您的模板中:

<input #input [ngModel]="value" (ngModelChange)="validate($event)" />

在您的 TS 文件中:

@ViewChild('input') input: ElementRef;

public validate(value) {
    if (value > 100)
        this.value = 100;
    if (value < 0)
        this.value = 0;
    this.input.writeValue(this.value); // force to update
}