创建仅允许号码的指令

问题描述 投票:0回答:2

我需要创建数字指令。因此通常实现整个应用程序。输入类型文本允许的键盘编号。

angular angularjs-directive
2个回答
0
投票

我创建了以下指令文件编号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" />

0
投票

请参阅此Working Demo

© www.soinside.com 2019 - 2024. All rights reserved.