You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:36:00