Angular 6 accordion using *ngIf and hidden directive

Reading Time: 2 minutes

Hi friends, Today I am going to share the simplest way to hide and show div to make angular 6 accordion. This is the need of every project as angular works on user events and many times we need that when user will click then we have to show some content and hide.

Earlier I used to do it by using JavaScript class selector which makes the code complex and messy. To solve this problem, I found a simple way. Please check the code below.

To make angular 6 accordion. First, declare the global variable in TypeScript file

We need one global variable in typescript file which can be accessed from the HTML file. We will make this variable as an array of type any.

Now place below code in HTML file.

In the below HTML, you can see I have added the click event. Default value of the variable is false. But, when the button is clicked then the variable, turns to true. I have placed this variable in the ngIf directive. so when the value turns to true, the div will be show.

If you want the other div to close then you can declare the function in typescript file and change the value of other variable to false. The variable which will have true value will  show.

We can do this same with the hidden operator.

The way we did *ngIf directive, we can do the same with the hidden directive. The only difference is we have to use (!) Not operator while checking the condition in the hidden directive.

Difference between *ngIf and hidden directive

*ngIf is structural directive which creates and deletes the element from DOM while the hidden directive simple use CSS display none and block property.

Please check the GitHub link to this tutorial and clone it to your PC. GitHub Link:- https://github.com/sudhanshu077/angula5-hide-show.

If you want to hire Full Stack Developer, you can read more about me :- Sudhanshu Sharma

Leave a Reply

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