输入编号上的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.
但是,您可以通过添加一条指令来规避此问题,因为它不会使您的组件杂乱无章,因此imo也更干净了.
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屋!