Angular - Pass data to parent component

2020-02-13 05:35发布

问题:

I have in my parent component this:

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

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?

回答1:

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

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.

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

Child component:

In your child component, declare an EventEmitter object.

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

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

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

Parent component:

In your parent component template, subscribe to this event:

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

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

updateObj(data) {
  // Do something.
}

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



回答2:

You should try using services to pass values from one component to another. https://www.youtube.com/watch?v=69VeYoKzL6I



标签: angular