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. We want to show/hide the paragraph as you check/uncheck the checkbox:
<div> <p>Check/Uncheck Checkbox to show/hide text</p> <input type="checkbox" (change)="showHideText();"> <p *ngIf="isDisplayed">This is some random text.</p> </div>
Now add the below code in your ts file:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { // Keep text hidden by default isDisplayed: boolean = false; // Fires whenever checkbox value changes showHideText() { // Show/hide text this.isDisplayed = !this.isDisplayed; // Add other stuff } }
Output:
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:
<div> <p>Check/Uncheck Checkbox to show/hide text</p> <input type="checkbox" (change)="showHideText($event);"> <p *ngIf="isDisplayed">This is some random text.</p> </div>
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.
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { // Keep text hidden by default isDisplayed: boolean = false; // Fires whenever checkbox value changes showHideText(event: any) { if (event.target.checked == true) { this.isDisplayed = true; } else { this.isDisplayed = false; } // Add other stuff } }
This code will also give you the same output as in the first example.
So, you can choose any of the two approaches to show or hide the text when the checkbox is checked or unchecked. Both works the same way.
That’s all for this article. Thanks for reading!