首页 > 解决方案 > 如何通过点击实现子组件与父组件的通信?

问题描述

我有两个组件。父组件包含一个按钮,如果我单击子按钮,它将被禁用,子组件将打开并包含关闭按钮。什么时候可以关闭子组件并启用父组件中的按钮?

我的代码:

// 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;
}

标签: angulartypescriptparent-child

解决方案


我重命名了一些变量以提高可读性。

将此代码也放在您的父组件中:

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().


推荐阅读