输入编号上的 NgModelChange 不更新视图 [英] NgModelChange on input number not updating the view
问题描述
我目前正在尝试创建一个输入数字,以防止用户输入高于 @Input() maxValue 的数字,我是这样实现的:
I'm currently trying to create an input number that prevent user to enter a number that is higher than a @Input() maxValue, I implemented it like this :
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 时,输入的数字不会更新.
It is working quite well but there is still a problem that I can't understand. I have a maxValue equals to 100, when I type 150 or 200, it change automatically to 100 but when I type 1000, the input number does not update.
当我尝试在控制台中或直接在 HTML 中显示该值时,模型正确地等于 100.您有什么想法可以帮助我理解这一点吗?
When I tried to show the value in the console or directly in the HTML, the model is correctly equals to 100. Do you have any idea to help me understand this ?
推荐答案
老实说,奇怪的错误,我测试过,它表现出相同的行为.
Weird bug to be honest, I tested and it showed the same behavior.
然而,你可以通过添加一个指令来规避这一点,这也更简洁,因为它不会让你的组件与一个函数混淆
However, you can circumvent this by adding a directive, which is imo also a lot cleaner because it doesnt clutter your component with a function
指令:
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
这篇关于输入编号上的 NgModelChange 不更新视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!