Angular 5:如何从父组件COMP1控制子组件COMP2的显示隐藏
嘿,这个需求其实很好实现,咱们用Angular的组件状态绑定+父子组件事件通信就能搞定,具体步骤我给你拆解清楚:
实现方案(Angular 5)
核心思路是让COMP1(父组件)统一管理COMP2的显示状态,同时让COMP2(子组件)能主动通知父组件切换自己的隐藏状态,具体操作如下:
1. 改造COMP1组件(父组件)
1.1 组件类代码(.ts文件)
先定义一个布尔变量控制COMP2的显示,再写两个方法分别处理“显示COMP2”和“接收COMP2的隐藏通知”:
import { Component } from '@angular/core'; @Component({ selector: 'comp1', templateUrl: './comp1.component.html' }) export class Comp1Component { // 控制COMP2显示的状态,初始设为false(默认隐藏) showComp2 = false; // 点击buttonA时触发,切换状态显示COMP2 handleShowComp2() { this.showComp2 = true; } // 接收COMP2传来的隐藏指令,切换状态隐藏COMP2 handleHideComp2() { this.showComp2 = false; } }
1.2 组件模板代码(.html文件)
用Angular的*ngIf指令绑定状态变量控制COMP2的显示,同时给按钮和子组件绑定对应事件:
<!-- 用*ngIf控制COMP2的渲染/销毁,实现显示隐藏 --> <comp2 *ngIf="showComp2" (hide)="handleHideComp2()"></comp2> <!-- buttonA绑定点击事件,触发显示COMP2 --> <button (click)="handleShowComp2()">buttonA</button>
2. 改造COMP2组件(子组件)
2.1 组件类代码(.ts文件)
用@Output()定义一个自定义事件,点击buttonB时发射这个事件通知父组件:
import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'comp2', templateUrl: './comp2.component.html' }) export class Comp2Component { // 定义输出事件,用来向父组件传递“隐藏自己”的指令 @Output() hide = new EventEmitter<void>(); // 点击buttonB时触发,发射隐藏事件 handleHideSelf() { this.hide.emit(); } }
2.2 组件模板代码(.html文件)
给buttonB绑定点击事件,触发上面定义的方法:
<button (click)="handleHideSelf()">buttonB</button>
逻辑说明
- 初始加载COMP1时,
showComp2为false,*ngIf会直接移除COMP2的DOM元素,实现默认隐藏; - 点击buttonA时,
handleShowComp2()把showComp2设为true,*ngIf会渲染COMP2,使其变为可见; - 点击buttonB时,COMP2通过
@Output发射hide事件,COMP1接收到事件后把showComp2设为false,COMP2再次被隐藏。
这样就完美实现你要的交互啦,代码都是Angular 5兼容的写法,直接用就行~
内容的提问来源于stack exchange,提问作者Anna
相关产品推荐
相关产品推荐

