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?

3
  • 1
    is this a similar issue? stackoverflow.com/questions/39236992/… Commented Jan 3, 2017 at 17:25
  • @Bean0341 sort of, but I don't want to use reactive forms, I'm trying to stick with template driven forms. Commented Jan 3, 2017 at 17:58
  • updated title so it's more clear. Commented Jan 3, 2017 at 17:59

2 Answers 2

20

try:

(keydown.space)="$event.preventDefault()"
Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.