0

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!

Onion
  • 85
  • 1
  • 9
  • Now I wonder if there's a way to directly style the ink bar on different mat-tabs? – Onion Mar 01 '21 at 15:15
  • When does it change from 'one' to 'two'? I find this article really helpful https://blog.angular-university.io/angular-debugging/ and it will even show you how to debug it. – AliF50 Mar 01 '21 at 15:44

1 Answers1

0

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'"
>
kvetis
  • 6,682
  • 1
  • 28
  • 48