[英]Create Directive for only allow number
i need to create Number Directive.我需要创建数字指令。 so commonly implement whole application.
所以通常实现整个应用程序。 input type text allowed keyboard number.
输入类型文本允许的键盘编号。
i created following directive file numbers-only.directive.ts我创建了以下指令文件 numbers-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();
}
}
}
and also i implement this component html file我也实现了这个组件 html 文件
<input type="text" class="form-control" name="zipcode" formControlName="zipcode" numbersOnly maxlength="5" />
Please refer this Working Demo .请参考这个工作演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.