如何仅在活动时显示 material 选项卡内容?

How to show material tab content only if is active?

我试图仅在选中时显示选项卡内容:

        <mat-tab label="contacts">
            <p-contacts [contacts]="selectedPanel.contacts"
                        *ngIf="tabGroup.selectedIndex === 1">
            </p-contacts>
        </mat-tab>

这是工作,但我得到了 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'. 那我做错了什么?

demo

*ngIf 通过在每次条件更改时添加或删除元素来物理更改 DOM。因此,如果条件在呈现给视图之前发生变化,则会抛出错误。 添加这将在 Angular 检查投射到 directive/component 的内容后强制更改检测周期:

import { ChangeDetectorRef, AfterContentChecked} from '@angular/core';

  constructor(private cdref: ChangeDetectorRef) { }

  ngAfterContentChecked() {

    this.cdref.detectChanges();

  }

STACKBLITZ

您可以 lazily load the tabs' 内容,方法是将内容放在 ng-template 中,使用 matTabContent 属性,如下所示:

<mat-tab-group  #tabGroup>
  <mat-tab  label="Firt">
    <ng-template matTabContent>
      Content 1
    </ng-template>
  </mat-tab>
  <mat-tab  label="Second">
    <ng-template matTabContent>
      Content 2
    </ng-template>
  </mat-tab>
  <mat-tab  label="Third">
    <ng-template matTabContent>
      Content 3
    </ng-template>
  </mat-tab>
</mat-tab-group>