7

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

yantrab
  • 2,482
  • 4
  • 31
  • 52
  • show us ts file also – Dusan Radovanovic May 24 '19 at 09:18
  • This blog helped me previously when I encountered this https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4 – Andrew Allen May 24 '19 at 09:20
  • 1
    https://stackblitz.com/edit/angular-wczj1f?file=app%2Ftab-group-basic-example.html – yantrab May 24 '19 at 09:22
  • your demo code and code in the question are different...plus I'm not sure what you're trying to acheive, what's wrong with the default materials tab? https://stackblitz.com/angular/jrkoremjemy?file=app%2Ftab-group-basic-example.html – Andrew Allen May 24 '19 at 09:30
  • @AndrewAllen it is different, but the same problem. i wont to load content to dom only if is active. – yantrab May 24 '19 at 09:36
  • 1
    https://material.angular.io/components/tabs/overview#lazy-loading – Jota.Toledo May 24 '19 at 09:40

2 Answers2

18

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>
wnvko
  • 1,985
  • 1
  • 14
  • 18
-1

*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

Ala Abid
  • 2,256
  • 23
  • 35