Angular 2 - 将 object 从 parent 传递给 child 组件进行修改

Angular 2 - pass object from parent to child component to modify

我知道从 parent 组件向 children 组件发送 object 就像通过 @input 发送它一样简单。

在我的例子中,我需要从 parent 发送一个 object 到它的 child 并在 child 端更改它并在 parent边立马

事实上,我想将 object 的引用发送到 child 而不是它的值。

这里有一个父子通信的例子,我们会在控制台看到parent传过来的object的child的changed value发生了变化

父组件:

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