1

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;
}
AlreadyLost
  • 767
  • 2
  • 13
  • 28

3 Answers3

1
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?

Community
  • 1
  • 1
bergben
  • 1,385
  • 1
  • 16
  • 35
  • sorry for dumb question, what is /\S/ ? – AlreadyLost Feb 25 '17 at 10:11
  • That's a regular expression: \S: "Matches a single character other than white space." See https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions – bergben Feb 25 '17 at 10:13
1

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

kind user
  • 40,029
  • 7
  • 67
  • 77
  • this will not work if there is sentence and it between there is space. I just want to disable only if all string is space – AlreadyLost Feb 25 '17 at 10:16
  • @AlreadyLost I got it. It has to be disabled if there are only whitespaces in the content. It works now. – kind user Feb 25 '17 at 10:19
0

enter image description here

trim() can be used to remove spaces.

Sagar C
  • 73
  • 1
  • 6