为什么 angular material 选项卡重新创建组件

Why angular material tabs recreate component

我的 angular 应用程序中有一个 material 设计。

        <mat-tab-group [dynamicHeight]="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>

当我再次选择选项卡 2 和选项卡 1 时,组件 (my-comp1, my-comp2) 重新创建。

您正在使用 Angular Material 个选项卡的延迟加载功能。

文档:https://material.angular.io/components/tabs/overview#lazy-loading

删除 matTabContent 将回退到预先加载并避免该问题。

当您使用 <ng-template matTabContent> 时,您会以惰性方式加载标签内容。删除它们以使用所有选项卡的预加载:

<mat-tab-group [dynamicHeight]="true">
    <mat-tab label="tab1">
        <div class="tab-content">
            <div class="map-container-outer">
                <div class="map-container">
                    <my-comp1></my-comp1>
                </div>
            </div>
        </div>
    </mat-tab>
    <mat-tab label="tab2">
      <div class="tab-content">
              <my-comp2></my-comp2>
      </div>
    </mat-tab>
</mat-tab-group>