angular - Angular - 重置其值后无法将数据发送到子组件
问题描述
在我的应用程序中,我有两个组件 - 我们称它们为 Parent 和 Child。单击时,我将数据从父级发送到子级并显示它。但是在子组件中,我还可以清除传入数据 - 将传入数据设置为空。清理后,我无法再从父级向子级发送和显示数据。这是片段:https ://stackblitz.com/edit/angular-ivy-1zdvqj?file=src/app/child/child.component.ts
解决方案
所以在ChildComponent
你设置id
为null
. 您只更新本地参考。ParentComponent
不知道 已在内部将ChildComponent
的值设置id
为null
。因此,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
。
阅读更多:
- Angular 2-way 绑定:https ://angular.io/guide/two-way-binding
- 输入和输出:https ://angular.io/guide/inputs-outputs
推荐阅读
- sql - SQL:如何存储和链接来自测试的大量数据
- reactjs - 如何使用 url 在 reactjs 中添加 json 文件作为资源?
- windows - 如何将 Windows 桌面上的目录配置为 Docker 卷?
- python - 如何追加到 Python 字典而不是更新
- ios - Crashlytics pod 仍在使用 UIWebView 生成 ITMS-90809:已弃用 API 使用
- excel - 如果单元格有值,则将数据粘贴到相邻单元格
- php - 如何在 woocommerce 中限制销售产品的 div
- regex - 制作一个包含我的列表项的文本文件并对其应用正则表达式
- git - 如何重置先前提交中的所有更改并将其与实际合并?
- java - 热敏打印机自动剪切未完成的收据,留下最后两行