簡體   English   中英

如何在角度2中創建僅允許文本的指令

[英]How to create directive in angular 2 that to allow text only

我創建了以下指令,僅允許使用鍵控代碼輸入數字(當我復制文本並將其粘貼到文本框中時,它接受但不接受)

是否可以使用替換和模式來限制數字或文本

angular 4指令(從stackoverflow站點引用)

import {Directive,HostListener,HostBinding,Input ,Renderer,ElementRef} from '@angular/core'


@Directive({
    selector: '[OnlyNumber]'
})

export class InputRestricter {

    constructor(private el: ElementRef) { }

    @Input() OnlyNumber: boolean;

    @HostListener('keydown', ['$event']) onKeyDown(event:any) {
        let e = <KeyboardEvent>event;
        if (this.OnlyNumber) {
            if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
                // Allow: Ctrl+A
                (e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
                // Allow: Ctrl+C
                (e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
                // Allow: Ctrl+V
                (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
                // Allow: Ctrl+X
                (e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
                // Allow: home, end, left, right
                (e.keyCode >= 35 && e.keyCode <= 39)) {
                // let it happen, don't do anything
                return;
            }
            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
        }
    }
}

我已經使用模式在angularJS中創建了指令並替換

app.directive('test',function(){
return{
    require:'ngModel',
    restrict :'A',
    link:function(scope,elm,attr,ngmodelctrl){
    ngmodelctrl.$parsers.push(function(val){
  //  var clean=val.replace(/^(0*)/,'');
  //var clean =val.replace(/[^0-9\.]/g,'')
  var clean =val.replace(/[^a-zA-Z\.]/g,'')
  ngmodelctrl.$setViewValue(clean);
    ngmodelctrl.$render();
    });
    }
}

})

我想要2個僅允許文本和另一個僅接受數字的指令

如果需要驗證輸入以僅接受數字或文本,則應使用角度驗證,而實際上您需要構建自己的驗證。 您會在這里找到一個很好的例子。

https://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html

但是,如果需要強制用戶僅輸入文本,則需要偵聽鍵並更改輸入的事件,然后,一旦輸入的值不符合您的要求,您應該編寫:

e.preventDefault();
return false;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM