How to toggle div on button click in Angular | Angular Tutorial

Share the post

Hello All, In the last topic we had discussed How to create a search filter in the angular application using ng2-search-filter. In this angular tutorial, We will learn How to toggle div on button click with the help of a simple example.

In this example, We will take two div & one button. The button will call a function where our logic will be written & according to our logic will show & hide the div. So, let’s start.

Step 1: Create an angular application by using the following command

ng new <APPNAME>

Now, move to our root project directory using the following command

cd <APPNAME>

Open the newly created angular project in Visual Studio Code. Use the following command to open the project.

code .

Step 2: HTML

Now, We will take two div & one button. The button will handle the toggleDiv() event. Also, handle the toggle condition with the help of selectDiv boolean value. Please see the source code for HTML as follows

<button (click)=toggleDiv()>Toggle Div</button>
<div *ngIf="!selectDiv">Div 1</div>
<div *ngIf="selectDiv">Div 2</div>

Step 3: TS

The main logic will handle by our ts code. We will create the toggleDiv() to handle our logic. Please see below the source code for the TS file.

selectDiv = false;

toggleDiv() {
    this.selectDiv = !this.selectDiv;
  }

Now, to see the output we have to write the following command in the visual studio code terminal

ng serve

Step 4: Output

output 1
Output 1
output 2
Output 2

If you see the output, You will identify that In Output 1 image the Div 1 is showing as we initialized selectDiv boolean value to false. Hence, Div 1 is showing by default. Now, If we click on the button toggleDiv() function will get called & make the selectDiv boolean value true. Hence, In the Output 2 image, we can clearly see it only showing Div 2.

Leave a Comment