为什么Angular Material的tab切换时会重新创建内部组件
现象产生原因
- 你代码中两个
mat-tab的内容都通过matTabContent指令包裹在<ng-template>标签内,该指令是Angular Material Tabs提供的内容懒加载标识 matTabContent的默认逻辑为:仅当标签被激活选中时才渲染对应模板内容,当标签切换失活后,会直接销毁对应标签的内容DOM以及绑定的组件实例- 因此从tab1切换到tab2时,tab1的
my-comp1实例会被销毁,同时创建tab2的my-comp2实例;切回tab1时,my-comp2会被销毁,my-comp1会重新初始化创建,就出现了切换时两个组件反复重建的现象
可选修复方案
如果希望标签切换时组件不被销毁,可以给mat-tab-group添加[preserveContent]="true"配置,修改后的代码示例如下:
<mat-tab-group [dynamicHeight]="true" [preserveContent]="true"> <mat-tab label="tab1"> <ng-template matTabContent> <div class="tab-content"> <div class="map-container-outer"> <div class="map-container"> <my-comp1></my-comp1> </div> </div> </div> </ng-template> </mat-tab> <mat-tab label="tab2"> <ng-template matTabContent> <div class="tab-content"> <my-comp2></my-comp2> </div> </ng-template> </mat-tab> </mat-tab-group>
添加该属性后,标签内容首次渲染后会保留在DOM结构中,失活时仅做视觉隐藏,不会销毁组件实例,切换时就不会触发组件重建逻辑。
内容的提问来源于stack exchange,提问作者barteloma
相关产品推荐
相关产品推荐

