Search code examples
cssangularangular-materialng-classmat-tab

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. with Ngclass on mat-tab-group


So I would like to make the mat-ink-bar have different colors from the same mat-tab-group. I'm using local reference and NgClass. The styles are working as expected, but in the console, it gives me this

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'one. Current value: 'two'.

Here is the code:
HTML:

<mat-tab-group
  class="<some other classes>"
  ...
  #tabGroup
  [ngClass]="tabGroup.selectedIndex === 1 ? 'one' : 'two'"
>

SCSS:

.one.mat-primary .mat-ink-bar{
  background: blue !important;
}

.two.mat-primary .mat-ink-bar{
  background: red !important;
}

When I was going over other posts on NgClass, it seems like the true and false values are constantly changing as well, then how come the method I'm using is giving me this error? Is it because other people choose to have variables changed inside NgAfterViewChecked or NgOnChanges, so changes are correctly detected?
Thank you!


Solution

  • this problem comes from the fact that the selectedIndex may change inside the tab group after the [ngClass] has been checked. You need to listen to (selectedTabChange) and track the selected index manually.

    Shortest code sample:

    <mat-tab-group 
      `(selectedTabChange)`="selectedTab = $event.index" 
      [ngClass]="selectedTab === 1 ? 'one' : 'two'"
    >