Reputation: 41
I have an application, where I have to pass data from child component to parent component. The data is an object.
The problem what I am facing is the data is being passed by ref, which means when my Child Component model data changes, the Parent Component Array (this.cashEntryItems) also being changes.
I tried to push some console.log() and but still no luck.
I am receiving the event data correctly but not able to pass data by value only (not linking to the child component object)
Here is the output of my console -
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)
I have pasted my code below.
Child Component -
Child Component.html
<form #itemForm="ngForm" (ngSubmit)="onSubmit()" *ngIf="isPageLoaded">
Child Component.ts
onSubmit() {
this.formSubmit.emit(this.cashEntryItem);
}
Parent Component
Parent Component.html
<app-child-component (formSubmit)="addItem($event)"></app-child-component>
Parent Component.ts
addItem(newItem: CashEntryItem) {
this.cashEntryItems.push(newItem);
this.cashEntryItems = this.cashEntryItems.slice(); //one suggestion from a blog - Not working
}
Upvotes: 1
Views: 1903
Reputation: 58019
just use a new variable in the input
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})
})
}
Upvotes: 2