AlreadyLost
AlreadyLost

Reputation: 827

Enable button on entering a character other than space in angular2

I have a comment section which is in form of text area and I want to enable a another button if user start typing some character(except space) into the textarea. How can I do that in angular2?

I already have it working but my problem is that the button gets enabled even if the user enter 'space' in text area. How can I correct this behavior so that only when user writes something the button gets enabled?

in html:

<textarea id="comments"
   class="comments-text"
   [(ngModel)]="text"
   (ngModelChange)="onAddComment($event)"
   name="text"></textarea>

<button [disabled]="EnableButton()">

in component:

 public onAddComment(event: string): void {
    this.passedString = event;
    }

 public EnableButton(): void {
    return !!this.passedString;
}

Upvotes: 1

Views: 3016

Answers (3)

Sagar C
Sagar C

Reputation: 73

enter image description here

trim() can be used to remove spaces.

Upvotes: 0

kind user
kind user

Reputation: 41893

You can check with every textarea value change, if it contains any other sign than a whitespace.

onAddComment() {
  if (this.text.replace(/\s/g, '').length == 0) {
    this.check = true;
  } else {
    this.check = false;
  }
}

Plunker

Upvotes: 1

bergben
bergben

Reputation: 1415

buttonIsDisabled:boolean=true;
public onAddComment(event: string): void {
   this.buttonIsDisabled=true;
   let passedString = event;
   if (/\S/.test(passedString)) {
       // string is not empty and not just whitespace
       // activate button
       this.buttonIsDisabled=false;
   }
}

<button [disabled]="buttonIsDisabled">

This should do the trick. See How can I check if string contains characters & whitespace, not just whitespace?

Upvotes: 1

Related Questions