Angular 2-将对象从父组件传递到子组件以进行修改

时间:2018-10-09 00:20:07

标签: angular parent-child

我知道从父组件向子组件发送对象就像通过@input发送对象一样容易。

对于我来说,我需要将一个对象从父对象发送到其子对象,并在子对象侧进行更改,然后立即在父对象侧看到此更改。

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

1 个答案:

答案 0 :(得分:0)

这是父子通讯的示例,我们将在控制台中看到从父传递的对象的子对象更改的值已更改。

父组件:

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