Angular2限制模板驱动的输入字段中的空白区域

时间:2017-01-03 17:22:49

标签: angular

前言:我不是试图使用反应形式

在Angular2中限制空格的正确方法是什么?我看到AngularJS的this答案,但我不确定在Angular2中是否有更好的方法可以做到这一点。说我有:

        <input
          placeholder="alert tag (25 max)"
          maxlength="25"
          value="alert"
          type="text"
          #alertTagInput
          [(ngModel)]="alertTag" >

用户当前可以输入空格,我该如何限制?

2 个答案:

答案 0 :(得分:15)

尝试:

(keydown.space)="$event.preventDefault()"

答案 1 :(得分:0)

使用此选项也可以设置角度误差。

表单字段

                         <input #name
                           formControlName="account_nick"
                           id="name"
                           maxlength="90"
                           minlength="5"
                           placeholder="eg. my name "
                           (keyup)="noSpace($event)"
                           required
                           type="text"
                           >

js代码

 this.countSpace = [];  //make a array 
 noSpace(key) { //log key and apply condition as you want 
        if (key.code === 'Space') {
            this.countSpace.push(key.code);
        }
        if (key.key.length === 1) { //if some one enter a only one value or one space 
            this.myform.controls['account_nick'].setErrors({'incorrect': true});
        }
        if (this.countSpace.length > 5) { // if name have more then 5 space 
            this.myform.controls['account_nick'].setErrors({'incorrect': true});
        }
    }