【问题标题】:How do I realize communication between child and parent component via click?如何通过点击实现子组件与父组件的通信?
【发布时间】:2020-09-16 12:45:54
【问题描述】:

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

我的代码:

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

【问题讨论】:

  • 您想从您的子组件中删除子组件吗?你不能这样做,但你可以向父级发出一个事件,然后将 showChild 设置为 false。

标签: angular typescript parent-child


【解决方案1】:

为了更好的可读性,我重命名了一些变量。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多