angular - 在Angular 8中通过事件发射器通过值(而不是通过引用)传递对象
问题描述
我有一个应用程序,我必须将数据从子组件传递到父组件。数据是一个对象。
我面临的问题是数据是由 ref 传递的,这意味着当我的子组件模型数据发生变化时,父组件数组(this.cashEntryItems)也会发生变化。
我尝试推送一些 console.log() 但仍然没有运气。
我正确接收事件数据,但无法仅按值传递数据(未链接到子组件对象)
这是我的控制台的输出 -
Console.log -> inside Parent Component.ts file
Input From Child Component
CashEntryItem {CompOperarator: {…}, description: "test", serviceType: ServiceType, amount: 100, …}
Before Push this.cashEntryItems -
[]
After Push this.cashEntryItems
[CashEntryItem]
0: CashEntryItem {CompOperarator: {…}, description: null, serviceType: ServiceType, amount: null, …}
length: 1
__proto__: Array(0)
我在下面粘贴了我的代码。
子组件 -
子组件.html
<form #itemForm="ngForm" (ngSubmit)="onSubmit()" *ngIf="isPageLoaded">
子组件.ts
onSubmit() {
this.formSubmit.emit(this.cashEntryItem);
}
父组件
父组件.html
<app-child-component (formSubmit)="addItem($event)"></app-child-component>
父组件.ts
addItem(newItem: CashEntryItem) {
this.cashEntryItems.push(newItem);
this.cashEntryItems = this.cashEntryItems.slice(); //one suggestion from a blog - Not working
}
解决方案
只需在输入中使用一个新变量
copyEntry:any;
@Input() set cashEntryItems(value){
this.copyEntry={...value} //if is an object
this.copyEntry=[...value] //if is an array of string or numbers;
//if is an array of object
this.copyEntry=[]
value.forEach(x=>{
this.copyEntry.push({...x})
})
}
推荐阅读
- c++ - C++17“静态内联”是否解决了静态初始化顺序惨败?
- javascript - 菜鸟问题->如何在 Reactjs 中获得一堵 html 标签而不返回“[Object object]”?
- python - 有没有办法给数据框中的特定数据一个类别,例如新闻标题的“技术”
- python - 从变量中的文本文件调用时,如何输入有限数量的数字?
- javascript - 搜索变量被赋予值的地方
- python - 带有python的outlook中的邮箱列表
- javascript - 获取失败?
- python - 我想做一个在python中旋转的栏
- python - 如何匹配文本和可选的重复标识符并将它们组合在一起?
- c - 在声明时将字符串文字分配给 char 数组与分配给 char 指针之间的区别?