当父组件中的对象属性更改时,如何更新子组件中的对象

时间:2018-08-22 06:53:52

标签: javascript angular typescript

我有2个组成部分

父项是

@Component({
  selector: 'parent',
  template: `
    <child [obj]="obj"> </child>
  `,
  styleUrls: [''],
})
export class parentComponent implements OnInit{

 obj = {
  id:1;
  name:'abc'
 }

}

子组件是

@Component({
  selector: 'child',
  templateUrl: '',
  styleUrls: [''],
})
export class ChildComponetimplements OnInit{

   @Input() obj : any;

}

如果我更改父对象obj中的任何属性,则子组件中的属性不会得到更新。

可能是因为obj引用未更改。

请为我提出解决方案。

3 个答案:

答案 0 :(得分:1)

您必须像下面一样使用ngOnChanges

父组件

export class AppComponent  {

  obj = {
    id:1,
    name:'abc'
  }

  name = 'Angular';

  changeObject() {
    this.obj.id++;
  }
}

父模板

<button (click)="changeObject()">Change Object</button>

<hello name="{{ name }}" [obj]="obj"></hello>

子组件

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

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1><p>{{ obj | json }}</p>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit, OnChanges { 
  @Input() name: string;
  @Input() obj;

  ngOnInit() {

  }

  ngOnChanges(changes) {
    this.obj = changes.currentValue ? changes.currentValue.obj : this.obj;
  }
}

工作示例在Stackblitz

答案 1 :(得分:0)

Stackblitz Demo

  obj = {
    id: 1,
    name: 'Hello'
  }

  changeObject() {
    this.obj.name = 'Hello change';
  }

答案 2 :(得分:0)

使用ngOnChanges收听输入属性的更改。您将把对象从父对象传递给子对象,并且当您作为子对象的输入传递的对象发生任何变化时,都会在子组件的SimpleChanges钩子中给ngOnChanges对象。

interface OnChanges {
  ngOnChanges(changes: SimpleChanges): void
}

示例

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnChanges {
  // TODO(issue/24571): remove '!'.
  @Input()
  prop !: number;

  ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value...
  }
}

有关ngOnChanges

的更多信息