我有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引用未更改。
请为我提出解决方案。
答案 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)
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...
}
}
的更多信息