Open In App

How to hide an HTML element via a button click in AngularJS ?

In this article, we will see how to use a toggle button feature to hide and display an element by button click in Angular. The toggle button is a user interface control that may be useful for situations when the user wants to switch between 2 states or conditions. For instance, in our smartphone, we usually turn off/on the button to wireless connected devices such as Bluetooth, Wifi, Airplane mode, etc. This kind of toggle button makes things easier to use in everyday life. This article will show how to make a toggle data button using Angular JS.

ngif Directive:The ngIf is an Angular structural directive that creates a template based on the value of the expression evaluation. The value of the expression should always be either True or False. When the expression inside the template evaluates to be true, then the block of code inside the then block is rendered and whereas the expression evaluates to be false, the else block, which is optional, gets rendered.
Syntax:



<div *ngIf = "condition">Content to render when condition is true.</div>

For the app.component.html file, we will use this toggleData() function to call the function in the Html 

<button (click)="toggleData()">Toggle Data</button>

For the app.component.ts file, we have defined a function that toggles the button to display or hide the content.



export class AppComponent {
 toDisplay = true;

 toggleData() {
   this.toDisplay = !this.toDisplay;
 }
}

 

Approach:

Project Structure: This will look like the following image
 

Example: 




<div *ngIf="toDisplay">
  <p>Click the below button to display and hide the data</p>
</div>
<button (click)="toggleData()">Toggle Data</button>




import { Component } from "@angular/core";
  
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
})
export class AppComponent {
  toDisplay = true;
  
  toggleData() {
    this.toDisplay = !this.toDisplay;
  }
}

Output: From the above output, we can see by clicking the Toggle Data button, we can able to display or hide the data.


Article Tags :