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