📅  最后修改于: 2023-12-03 15:31:20.641000             🧑  作者: Mango
This article provides a tutorial on how to hide and show divs on button click in an Angular 8 application. This functionality can be useful for creating collapsible content, dropdown menus, and other similar UI components.
Before proceeding with this tutorial, make sure you have the following installed on your system:
First, create a new Angular project using the ng new
command.
ng new my-angular-app
Next, add HTML and CSS to create a simple UI with two divs, one of which is hidden and only appears when the button is clicked.
<div class="container">
<div class="content" *ngIf="showDiv">
<h1>Example</h1>
<p>This content appears when the button is clicked!</p>
</div>
<button (click)="toggleDiv()">Toggle Div</button>
</div>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.content {
display: none;
flex-direction: column;
align-items: center;
text-align: center;
}
The *ngIf
directive is used to show or hide the div based on the value of the showDiv
variable.
Finally, add the component logic to handle the button click event and update the showDiv
variable.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
showDiv = false;
toggleDiv() {
this.showDiv = !this.showDiv;
}
}
The toggleDiv()
method simply toggles the value of the showDiv
variable between true
and false
when the button is clicked.
In conclusion, the ability to hide and show divs on button click is a useful feature to have in any Angular application. By following the steps outlined in this tutorial, you can easily implement this feature in your own projects.