如何手动触发更改事件 – angular2
鉴于以下组件:
@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"); } } 据我所知,除非更改完整的项目对象,否则angular2无法识别项目的更改.因此,我想在调用updateItem方法时手动为项发出更改事件.然后,使子组件,即CompB重新渲染,就像角度检测到常规方式的变化一样. 目前,我所做的是为CompB实现ngOnInit方法,并通过ViewChild链接在updateItem方法中调用该方法.故事的另一部分是我的实际源码有像someArray这样的对象,我想在每个渲染中重置它.我不确定重新渲染是否会重置someArray.目前,我正在ngOnInit方法中重置它们. 所以,我的问题是:如何触发对父对象的更深层元素的更改进行重新渲染? 谢谢
这并不是那么简单.您必须区分在对象变异时触发ngOnChanges和子组件的DOM更新. Angular无法识别该项已更改且未触发ngOnChanges生命周期钩子,但如果您引用模板中项目的特定属性,DOM仍将更新.这是因为保留了对象的引用.因此有这种行为:
您不必特别做任何事情,因为您仍然会在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.在这种情况下,一种方法是在CompB的ngDoCheck钩子中进行手动检查: 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(); } } } 您可以在以下文章中找到更多信息: > Everything you need to know about change detection in Angular文章. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |