yantrab
yantrab

Reputation: 2662

How to show material tab content only if is active?

I trying to show tab content only if is selected:

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

it is work, but i got ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'. So what do i did wrong?

demo

Upvotes: 7

Views: 5670

Answers (2)

wnvko
wnvko

Reputation: 2120

You can lazily load the tabs' content by put the content in ng-template with matTabContent attribute like this:

<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>

Upvotes: 18

Ala Abid
Ala Abid

Reputation: 2326

*ngIf physically changes the DOM by adding or removing the element every time the condition changes. So if the condition changes before it is rendered to the view the error is thrown. Adding this will force a change detection cycle after Angular checks the content projected into the directive/component:

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

  constructor(private cdref: ChangeDetectorRef) { }

  ngAfterContentChecked() {

    this.cdref.detectChanges();

  }

STACKBLITZ

Upvotes: -1

Related Questions