如何拥有具有反应形式的
<input type="number">
?
没有原生的数字验证器(https://angular.io/api/forms/Validators),但你可以轻松地做一个模式
Validators.pattern('^[0-9]*$')
。
但即使使用验证器,用户仍然可以输入任何字符,然后得到或不得到错误。我怎样才能有一个只接受数字的简单输入?
type
HTML 属性完全被 matInput 忽略,我刚刚读到材料不会添加行为(https://github.com/angular/components/issues/25107),但该行为是本机的浏览器并且已经存在。
这是一个使用相同的 html 本机输入元素和属性
type="number"
的工作示例,看起来效果很好!
<form class="example-form">
<mat-form-field class="example-full-width">
<mat-label>Favorite food</mat-label>
<input
matInput
placeholder="Only accepts numbers"
value="123"
type="number"
/>
</mat-form-field>
</form>
使用指令强制输入字段,这将确保输入字段只接受数字。
创建一个如下所示的 OnlyNumberDirective 并在模板中使用它
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appOnlyNumber]'
})
export class OnlyNumberDirective {
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();
}
}
}
该指令仅接受输入字段中的数字值,并在用户键入时过滤掉任何非数字字符。