我需要创建数字指令。因此通常实现整个应用程序。输入类型文本允许的键盘编号。
我创建了以下指令文件编号only.directive.ts
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: 'input[numbersOnly]'
})
export class NumberDirective {
constructor(private _el: ElementRef) { }
@HostListener('input', ['$event']) onInputChange(event) {
const initalValue = this._el.nativeElement.value;
this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
if (initalValue !== this._el.nativeElement.value) {
event.stopPropagation();
}
}
}
而且我也实现了该组件html文件
<input type="text" class="form-control" name="zipcode" formControlName="zipcode" numbersOnly maxlength="5" />
请参阅此Working Demo。