1
votes

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
  }
1
Try emitting a copy of the values: this.formSubmit.emit(JSON.parse(JSON.serialize(this.cashEntryItem)))David
Thanks David for the suggestion. This worked for me. Passing as String has helped me. Got the below statement from one blog:- if we pass objects in the @Output() decorator then it would be passed as a reference, and if we pass primitive types, then it would be passed as a value.k.chinni66

1 Answers

2
votes

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}) 
   })
}