Toggle a Div on Button Click Angular

In this section, we are going to learn how we can toggle a Div by clicking on a button. We will use Angular to do this. In our below example, we will learn the use of toggle elements. In our application, we are going to use ngIf and hidden to toggle div on an event of button click. In our Angular application, we can use various versions of Angular such as Angular 6, 7, 8, 9, 10, and 11, to show, use, and hide toggle div on click event.

In our section, we are going to explain two examples to learn about toggle elements on click. In our first example, we will use if with the *ngIf. In the second example, we will use if with [hidden]. We will use two methods so that we can create the button. When the function is clicked by us, it will be set as true, and the variable will be set to a false value. Our element or div can be shown or hidden by using the variable.

Example 1:

In our first example, we are going to use if with the *ngIf.

app.component.html

<h1> Example of Toggle a Div on Click on a Button using Angular /h1>  

<button (click)=toggleDisplayDiv() >Toggle display Div</button>  

<div [hidden]="isShowDiv">This Div is from Javatpoint.com.</div>/div>

  

app.component.ts

import { Component } from '@angular/core';  

    

@Component({  

  selector: 'app-root',  

  templateUrl: './app.component.html',  

  styleUrls: ['./app.component.css']  

})  

export class AppComponent {  

  title = 'appComponent';  

      

  isShowDiv = false;  

     

  toggleDisplayDiv() {  

    this.isShowDiv = !this.isShowDiv;  

  }  

}

Example 2:

In the second example, we are going to use if with [hidden].

app.component.html

<h1> Example of Toggle a Div on Click on a Button using Angular </h1>  

<button (click)=toggleDisplayDivIf() >Toggle display Div If</button>  

<div *ngIf="!isShowDivIf"> This Div If is from Javatpoint.com.</div>

app.component.ts

import { Component } from '@angular/core';  

    

@Component({  

  selector: 'app-root',  

  templateUrl: './app.component.html',  

  styleUrls: ['./app.component.css']  

})  

export class AppComponent {  

  title = 'appComponent';  

      

  isShowDivIf = false;  

    

  toggleDisplayDivIf() {  

    this.isShowDivIf = !this.isShowDivIf;  

  }  

}

Now our above code is ready, and we can run it on our local. When we run this, the following output will be generated:

Toggle a Div on Button Click Angular

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *