首页 > 解决方案 > Angular - 重置其值后无法将数据发送到子组件

问题描述

在我的应用程序中,我有两个组件 - 我们称它们为 Parent 和 Child。单击时,我将数据从父级发送到子级并显示它。但是在子组件中,我还可以清除传入数据 - 将传入数据设置为空。清理后,我无法再从父级向子级发送和显示数据。这是片段:https ://stackblitz.com/edit/angular-ivy-1zdvqj?file=src/app/child/child.component.ts

标签: angular

解决方案


所以在ChildComponent你设置idnull. 您只更新本地参考。ParentComponent不知道 已在内部将ChildComponent的值设置idnull。因此,ChildComponent需要发出更改并通知ParentComponent所做的更改。

为了解决这个问题,我们在盒子运算符和概念中使用[()]了香蕉。@Output EventEmitter

在您的ParentComponent.html中,将您的ChildComponent输入更改为 2-way binding:

<app-child [(id)]="elementId"></app-child>

在您的ChildComponent中,添加一个新EventEmitter的以通知对输入所做的任何更改id

@Output() idChange: EventEmitter<number> = new EventEmitter<number>();

然后在你的reset函数中,发出更新的值;

reset() {
    this.id = null;
    this.idChange.emit(this.id);
}

当更新id从发出时ChildComponent;它在 中被接收,ParentComponent然后也ParentComponent更新它的引用null

阅读更多:

  1. Angular 2-way 绑定:https ://angular.io/guide/two-way-binding
  2. 输入和输出:https ://angular.io/guide/inputs-outputs

推荐阅读