我有一个应用程序,在那里我必须将数据从子组件传递到父组件。数据是一个对象。
我面临的问题是数据由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);
}
父组件
Parent Component.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})
})
}