【问题标题】:Angular2 restrict white space within template-driven input fieldAngular2限制模板驱动的输入字段中的空白
【发布时间】:2017-05-17 20:49:25
【问题描述】:

前言:我不想使用响应式表单

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

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

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

【问题讨论】:

  • 这是一个类似的问题吗? stackoverflow.com/questions/39236992/…
  • @Bean0341 有点像,但我不想使用响应式表单,我正在尝试坚持使用模板驱动的表单。
  • 更新了标题,使其更加清晰。

标签: angular


【解决方案1】:

试试:

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

【讨论】:

  • 效果很好,我也做了onDrag="return false" onDrop="return false" onPaste="return false",因为我不希望用户将内容粘贴到输入框中
【解决方案2】:

用这个也设置角度误差试试这个。

表单域

                         <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});
        }
    }

【讨论】:

    猜你喜欢
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多