首页 > 解决方案 > Angular 2 - 将对象从父组件传递到子组件以进行修改

问题描述

我知道将对象从父组件发送到子组件就像通过@input 发送它一样简单。

在我的情况下,我需要将一个对象从父级发送到其子级,并在子级进行更改,并立即在父级看到此更改。

事实上,我想将对象的引用发送给孩子而不是它的值。

标签: angularparent-child

解决方案


这是一个父子通信的示例,我们将在控制台中看到从父传递的对象的子对象的更改值发生了变化。

父组件:

import { Component, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <child [childProp]="parentProp" (childPropChange)="fromChild($event)"></child>
  `
})
export class AppComponent implements OnChanges {
  parentProp = {value1: "value1", value2: "value2"};

  ngOnChanges(c: SimpleChanges) {
    console.log('Parent changes: This doesnt happen often ', c);
  }

  fromChild(val) {
    console.log('Parent: receive from child, ', val.value1);
    console.log('Parent: receive from child, ', val.value2);
    console.log('Parent: receive from child, ', this.parentProp.value1);
    console.log('Parent: receive from child, ', this.parentProp.value2);
  }
}

子组件:

import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'child',
  template: `
    <h3>Child Component with {{childProp}}</h3>
    <button (click)="fire()">Talk to parent</button>
  `
})
export class ChildComponent implements OnChanges {
  @Input() childProp;
  @Output() childPropChange = new EventEmitter<{}>();

  ngOnChanges(changes: SimpleChanges) {
    console.log('in child changes with: ', changes);
  }

  fire() {
    this.childProp.value1 = "value1 changed";
    this.childProp.value2 = "value2 changed";
    this.childPropChange.emit(this.childProp);
  }
}

您可以在This stackblidtz中看到结果

在父组件中,我们有这个对象:

parentProp = {value1: "value1", value2: "value2"};

在子组件中,我们更改从父组件接收到的对象并以这种方式发出值:

this.childProp.value1 = "value1 changed";
this.childProp.value2 = "value2 changed";
this.childPropChange.emit(this.childProp);

您可以在控制台中看到此结果:

Parent: receive from child,  value1 changed
Parent: receive from child,  value2 changed
Parent: receive from child,  value1 changed
Parent: receive from child,  value2 changed

推荐阅读