Angular-将数据传递到父组件 [英] Angular - Pass data to parent component

查看:95
本文介绍了Angular-将数据传递到父组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的父组件中有这个:

 obj: any = { row1: [], row2: [], total: [], sumTotal: 0 };

我将obj传递给子组件:

I pass obj to child component :

<tr table-tr-tr *ngFor="let key1 of channels[name];let i=index" [key1]="key1" [data]="array" [field]="key1"
      [width]="width" [plantype]="plantype" [custom]="custom" [i]="i" [row]="row" [obj]="obj"></tr>
  </table>

在子组件中,我有这个:

In child component i have this:

  ngOnInit() {
    for (let index = 0; index < this.data.length; index++) {
      this.array.push({ code: index, value: 0 });
    }
    this.obj['row2'][this.field] = this.array;

  }

在此子组件中,我还有另一个子组件,在该子组件中我更改了数组的值,但在父对象上未更改它.任何建议,我怎么能做到这一点?

Inside this child component i have another child component where i change values of array but its not changing on my parent object. Any suggestion how can i achive this?

推荐答案

在此子组件中,我还有另一个子组件,其中 更改数组的值,但不会更改我的父对象.

Inside this child component i have another child component where i change values of array but its not changing on my parent object.

在Angular中,父组件和子组件之间的数据流不是双向的.因此,您在子组件中所做的更改不会反映在父组件中.

Data flow between parent and child components is not two-way in Angular. So the changes you make in a child component won't be reflected in the parent component.

您可以使用EventEmitter从子组件向父组件发出事件.

You can use EventEmitter to emit events from child component to parent component.

子组件:

在子组件中,声明一个EventEmitter对象.

In your child component, declare an EventEmitter object.

@Output() updateObjDataEvent: EventEmitter<any> = new EventEmitter<any>();

然后在子组件的任何位置使用emit方法将数据发送到父组件.

Then use emit method from anywhere in the child component to send data to parent component.

// Update parent component data.
this.updateObjDataEvent.emit(obj);

父组件:

在您的父组件模板中,订阅此事件:

In your parent component template, subscribe to this event:

<app-child-component-selector (updateObjDataEvent)="updateObj($event)">
</app-child-component-selector>

然后在您的父组件中,创建updateObj()方法来处理子组件中的数据更新.

Then in your parent component, create updateObj() method to handle data updates from child component.

updateObj(data) {
  // Do something.
}

updateObj()方法中,您可以更新父组件的数组对象.

In the updateObj() method, you can update your parent component's array object.

这篇关于Angular-将数据传递到父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆