在Angular 10中显示或隐藏子组件
在这篇文章中,我们将看到如何在Angular中显示或隐藏子组件。
- 让我们从创建一个新的项目开始。创建一个新的文件夹并初始化一个新的angular项目。运行该项目以验证它是否工作。
ng new myProject
ng serve -o
- 这将在当前目录下创建一个新项目。现在我们可以清除app.component.html文件并创建一个子组件,以便演示如何显示或隐藏它。
ng generate component comp1
- 现在,设置部分已经结束。让我们在我们的app.component.html文件中添加这些组件。
<app-comp1></app-comp1>
- 我们将创建一个按钮来显示和隐藏该组件。让我们在app.component.html文件中添加按钮代码。
<button type="button" (click)="showhideUtility()">
{{buttonTitle}}
</button>
- 这里showhideUtility()是一个方法,buttonTitle是一个变量,我们需要在app.component.ts文件中定义。
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'myProject';
buttonTitle:string = "Hide";
showhideUtility(){
}
}
- 我们的子组件仍然是空白的,所以让我们添加一些内容。转到comp1.component.html,添加以下代码。
<div>
This is the Child Component
</div>
- 并在comp1.component.css中添加一些css,以便得到一个漂亮的视图。
div{
height:200px;
width: 200px;
border: 2px lightblue solid;
border-radius: 10px;
background-color: lightgreen;
}
- 现在回到app.component.ts,添加一个新的属性’visible’,它将是一个布尔变量来定义显示/隐藏状态。当用户触发显示隐藏方法时,它应该翻转’visible’变量的值。所以最后我们的app.component.ts将看起来像这样。
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'myProject';
buttonTitle:string = "Hide";
visible:boolean = true;
showhideUtility(){
this.visible = this.visible?false:true;
this.buttonTitle = this.visible?"Hide":"Show";
}
}
- 为comp1添加ngIf指令,以显示或隐藏该组件。所以最后app.component.html看起来像这样。
<app-comp1 *ngIf="visible"></app-comp1>
<button type="button" (click)="showhideutility()">{{buttonTitle}}</button>
- 现在,保存所有文件,并使用.NET技术运行该项目。
ng serve -o
该项目将默认运行在http://localhost:4200。你将会看到这样的输出。

单击 “显示 “按钮时

当隐藏按钮被点击时
极客教程