angular - 如何通过点击实现子组件与父组件的通信?
问题描述
我有两个组件。父组件包含一个按钮,如果我单击子按钮,它将被禁用,子组件将打开并包含关闭按钮。什么时候可以关闭子组件并启用父组件中的按钮?
我的代码:
// Parent
<app-child (currentChild)="setCurrentChild($event)" *ngIf="showChild"></app-child>
<button type="button" (click)="openChild()" [disabled]="isDisabled">Child</button>
public showChild = false;
public isDisabled = false;
openChild() {
this.showChild = true;
this.isDisabled = true;
}
// Child
<button class="btn-close" mat-button (click)="closeChild()">close</button>
@Output() public currentChild: EventEmitter<any> = new EventEmitter<any>();
closeChild() {
this.showChild = false;
this.isDisabled = false;
}
解决方案
我重命名了一些变量以提高可读性。
将此代码也放在您的父组件中:
closeChild() {
this.showChild = false;
this.isDisabled = false;
}
然后修改你的子元素:
<app-child (onCloseChild)="closeChild()" *ngIf="showChild"></app-child>
在您的子文件中,您执行以下操作:
<button class="btn-close" mat-button (click)="sendCloseEvent()">close</button>
@Output() public onCloseChild: EventEmitter<any> = new EventEmitter<any>();
sendCloseEvent() {
this.onCloseChild.emit(true);
}
这将通过发射器发送一个事件,您的父母正在收听它。一旦到达父级,它就会调用closeChild()
.
推荐阅读
- flutter - 如何从命令行添加包?
- vue.js - Vue Kendo Scheduler 如何从外部源实现 Drop 事件:即列表
- java - Docker 和 Maven 依赖离线
- css - 仅在 Bootstrap 3 轮播上显示 3 个轮播指示器
- sql-server - 索引匹配 (excel) 的等效 SQL 查询以更新现有表中的列
- kubernetes - kubectl 和 minikube-kubectl 的区别
- reactjs - 在玩笑中模拟功能组件会引发“无效变量访问”错误
- reactjs - React Native:超过最大更新深度错误
- python - 如何在 django 中注册时使用此功能更新用户字段?
- html - HTML中的属性和属性有什么区别?