2

Preface: I am not trying to use reactive forms

What is the proper way to restrict white space in Angular2? I see this answer for AngularJS, but I am not sure if there is a better way to do this in Angular2. Say I have:

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

The user can currently type in whitespace, how do I restrict that?

Community
  • 1
  • 1
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177

2 Answers2

20

try:

(keydown.space)="$event.preventDefault()"
Meir
  • 14,081
  • 4
  • 39
  • 47
  • 3
    Worked great, I also did `onDrag="return false" onDrop="return false" onPaste="return false"` because I don't want users pasting stuff into the input box – Syntactic Fructose Jan 03 '17 at 17:57
0

Try this one using this also set angular error.

form field

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

js code

 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});
        }
    }
Harish Verma
  • 548
  • 7
  • 17