How to Display Text when Checkbox is Checked in Angular?

To display a text when the checkbox is checked, you can add a *ngIf directive in the element that contains the text and bind it to a flag(eg. isDisplayed) in your ts file.

If the value of the flag is true, the text will be displayed otherwise if it is false, the text will be hidden. We will be using this concept to show/hide the text.

But, we want to show or hide the text based on the current state of the checkbox i.e. if the checkbox is checked the text will be visible otherwise it will be hidden. Therefore, we have to toggle the value of the flag whenever the checkbox value is changed.

Let’s say we have a checkbox and a paragraph element that contains the text:

<input type="checkbox" (change)="showHideText();">
<p *ngIf="isDisplayed">This is some random text.</p>

You have to add the below code in your ts file:

isDisplayed: boolean = false;

// Called whenever checkbox value changes
showHideText(){
  
  // Toggle the flag value
  this.isDisplayed = !this.isDisplayed;

  // Add other stuff

}

The showHideText() function will be called every time you click on the checkbox because we have bound it with the (change) event.

Instead of toggling the value of the isDisplayed flag, you can also check the current state of the checkbox and change the value of the isDisplayed flag accordingly.

That is, if the checkbox is checked, set the flag’s value to true otherwise set it to false.

To keep track of the checkbox’s current state, you have to pass $event inside the event handler function which contains the current state of the checkbox.

Here is the modified template file:

<input type="checkbox" (change)="showHideText($event);">
<p *ngIf="isDisplayed">This is some random text.</p>

In your ts file, you can check whether the checkbox is checked using the event i.e. if event.target.checked is true the checkbox is checked otherwise it is unchecked.

// Called whenever checkbox value changes
showHideText(event:any){
  
  if(event.target.checked==true){
    this.isDisplayed = true;
  }
  else{
    this.isDisplayed = false;
  }

  // Add other stuff

}