鉴于以下组件:
@Component({
selector: 'compA',
template: template: `<compB [item]=item></compB>`
})
export class CompA {
item:any;
updateItem():void {
item[name] = "updated name";
}
}
@Component({
selector: 'compB',
template: template: `<p>{{item[name]}}</p>`
})
export class CompB implements OnInit{
@Input() item: any;
someArray: any[];
ngOnInit():void {
someArray.push("something");
}
}
据我所知,除非更改完整的item
对象,否则angular2无法识别item
上的更改。因此,当调用item
方法时,我想为updateItem
手动发出更改事件。然后,使子组件即CompB
重新渲染,就像角度检测到常规方式的变化一样。
目前,我所做的是为ngOnInit
实现CompB
方法,并通过updateItem
链接在ViewChild
方法中调用该方法。故事的另一部分是我的实际来源有像someArray
这样的对象,我想在每个渲染中重置它。我不确定重新渲染重置someArray
虽然。目前,我正在使用ngOnInit
方法重置它们。
所以,我的问题是:如何触发对父对象的更深层元素的更改进行重新渲染?
谢谢
据我所知,除非更改完整的项目对象,否则angular2无法识别项目的更改。
这并不是那么简单。您必须区分在对象发生变异时触发ngOnChanges
和子组件的DOM更新。 Angular不承认item
已更改且未触发ngOnChanges
生命周期钩子,但如果您在模板中引用item
的特定属性,DOM仍将更新。这是因为保留了对象的引用。因此有这种行为:
然后,使子组件,即CompB重新渲染,就像角度检测到常规方式的变化一样。
您不必特别做任何事情,因为您仍将在DOM中进行更新。
您可以插入更改检测器并像这样触发它:
@Component({
selector: 'compA',
template: template: `<compB [item]=item></compB>`
})
export class CompA {
item:any;
constructor(cd: ChangeDetectorRef) {}
updateItem():void {
item[name] = "updated name";
this.cd.detectChanges();
}
}
这会触发当前组件及其所有子组件的更改检测。
但是,它不会对你的情况产生任何影响,因为即使Angular没有检测到item
的变化,它仍会对子B
组件运行更改检测并更新DOM。
除非你使用ChangeDetectionStrategy.OnPush
。在这种情况下,一种方法是在ngDoCheck
的CompB
钩子中进行手动检查:
import { ChangeDetectorRef } from '@angular/core';
export class CompB implements OnInit{
@Input() item: any;
someArray: any[];
previous;
constructor(cd: ChangeDetectorRef) {}
ngOnInit():void {
this.previous = this.item.name;
someArray.push("something");
}
ngDoCheck() {
if (this.previous !== this.item.name) {
this.cd.detectChanges();
}
}
}
您可以在以下文章中找到更多信息: