📌  相关文章
📜  https:stackoverflow.com 问题 58589741 angular-8-hide-divs-and-show-div-on-button-click (1)

📅  最后修改于: 2023-12-03 15:31:20.641000             🧑  作者: Mango

Angular 8 Hide Divs and Show Div on Button Click
Introduction

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.

Prerequisites

Before proceeding with this tutorial, make sure you have the following installed on your system:

  • Node.js and NPM
  • Angular CLI
Step-by-Step Guide

1. Create a new Angular project

First, create a new Angular project using the ng new command.

ng new my-angular-app

2. Add the HTML and CSS

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.

3. Add the Component logic

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.

Conclusion

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.