Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 01 Aug, 2021
Geek Week

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:

  • First, wrap the content inside a <div> tag in an Html file.
  • Now take a variable “toDisplay” and bind it to the <div> tag.
  • In an HTML file, include a button and attach a function call to it whenever the user clicks on it.
  • In the ts file, implement the function and now toggle the toDisplay variable between true and false.
  • Once the above implementation is done, start the application

Project Structure: This will look like the following image
 

Example: 

app.component.html 




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

app.component.ts




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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :