首页 > 解决方案 > 在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
  }

标签: angulareventemitterpass-dataangular-event-emitter

解决方案


只需在输入中使用一个新变量

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

推荐阅读