在Angular中,可以使用模板驱动表单或响应式表单来验证输入。这里提供一种模板驱动表单的解决方法。
首先,我们需要在输入框中设置一个指令(directive),这个指令用于限制输入框只能输入数字:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: 'input[numbersOnly]'
})
export class NumbersOnlyDirective {
constructor(private el: ElementRef) { }
@HostListener('input', ['$event']) onInputChange(event) {
const initialValue = this.el.nativeElement.value;
this.el.nativeElement.value = initialValue.replace(/[^0-9]*/g, '');
if ( initialValue !== this.el.nativeElement.value) {
event.stopPropagation();
}
}
}
在输入框模板中引入这个指令:
然后就可以测试此时输入框是否只允许输入数字。
上一篇:Angular中的输入变化延迟