📅  最后修改于: 2023-12-03 15:15:45.690000             🧑  作者: Mango
In this post, we will discuss how to hide and show divs on button click using Angular 8.
The problem statement is to show/hide divs based on button clicks. Each button should display a different div and hide the others.
We can achieve this functionality using Angular directives and event bindings.
First, we need to define the divs we want to hide and show in the HTML file:
<div class="container">
<button (click)="showDiv(1)">Show Div 1</button>
<button (click)="showDiv(2)">Show Div 2</button>
<button (click)="showDiv(3)">Show Div 3</button>
<div [hidden]="divToShow !== 1">Div 1</div>
<div [hidden]="divToShow !== 2">Div 2</div>
<div [hidden]="divToShow !== 3">Div 3</div>
</div>
We have defined three buttons, each with a click event bound to the showDiv
method passing in the id of the div we want to show. We have also defined three divs with a hidden attribute set to true based on if the divToShow
variable is equal to the id of the div.
Now, we need to define the showDiv
method in our component:
divToShow: number = 1;
showDiv(divNumber: number) {
this.divToShow = divNumber;
}
We have defined a divToShow
variable that will store the id of the currently visible div. We have also defined the showDiv
method that takes in the id of the div we want to show/hide and sets the divToShow
variable to that id.
The final step is to add the necessary styles to hide/show the divs:
.container > div {
display: none;
}
.container > div:first-child {
display: block;
}
We have defined the container to have all child divs with display: none
, which will hide all divs by default. We have then defined the first child div to have display: block
, which will show the first div by default.
With these steps, we have achieved the ability to hide/show divs on button click in our Angular 8 application.
I hope this post was helpful. Thanks for reading!