如何在Angular 2中强制组件重新渲染?为了调试的目的,使用Redux时,我想强制一个组件重新渲染它的视图,这是可能的吗?
发布于 2018-11-09 00:59:58
这里的其他答案提供了触发更改检测周期的解决方案,这些周期将更新组件的视图(这与完全重新呈现不同)。
完全重新渲染,这将销毁并重新初始化组件(调用所有生命周期挂钩并重建视图),可以通过以下方式使用ng-template
、ng-container
和ViewContainerRef
来完成:
<div>
<ng-container #outlet >
</ng-container>
</div>
<ng-template #content>
<child></child>
</ng-template>
然后,在引用了#outlet
和#content
的component中,我们可以清除outlets的内容并插入子组件的另一个实例:
@ViewChild("outlet", {read: ViewContainerRef}) outletRef: ViewContainerRef;
@ViewChild("content", {read: TemplateRef}) contentRef: TemplateRef<any>;
private rerender() {
this.outletRef.clear();
this.outletRef.createEmbeddedView(this.contentRef);
}
此外,应该在AfterContentInit
钩子上插入初始内容:
ngAfterContentInit() {
this.outletRef.createEmbeddedView(this.contentRef);
}
完整的工作解决方案可以在这里找到https://stackblitz.com/edit/angular-component-rerender。
https://stackoverflow.com/questions/35105374
复制相似问题