简体   繁体   English

为仅允许编号创建指令

[英]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.

相关问题 如何在角度2中创建仅允许文本的指令 - How to create directive in angular 2 that to allow text only 如何只允许复制粘贴数字指令 angular 9 - How to allow copy paste only for number directive angular 9 什么是允许只插入正数而不允许插入负数的最佳指令 - What is the best directive to allow insert only positive number and not allow to insert minus 如何创建角度指令文本框只允许数字空格和分数 - How to create angular directive text box only allow numbers space and fraction 指令允许用户以角度4输入带有2位十进制值的数字 - Directive to allow user to enter number with 2 digit decimal value in angular 4 Angular:如何使用指令在文本框中仅允许 integer - Angular: How to allow only integer in the textbox using Directive Angular 中只允许一位小数和正数 - Allow only one decimal and only positive number in Angular 仅限角度数字的指令,接受两个小数点(0 ..) - angular number-only directive accepting two decimals (0..) 验证输入文本框的指令,仅允许数字,负号和十进制值 - Directive to validate input textbox to allow only numbers, a negative sign and a decimal value 如何使用指令仅允许在输入类型“ tel”中输入数字(0-9)-Ionic 3 Angular 5 - How to only allow digits(0-9) to be entered in input type 'tel' using directive - Ionic 3 Angular 5
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM