'Angular routerLinkActive only updates after clicking somewhere on the screen
Using Angular 13
I have a side menu which I build like this
<mat-nav-list>
<a mat-list-item *ngFor="let page of pages" [routerLink]="page.link" routerLinkActive="is-active">
<mat-icon style="padding-right:5px;">{{page?.icon}}</mat-icon>
<span [@animateText]="linkText ? 'show' : 'hide'">{{ page?.name }} </span>
</a>
</mat-nav-list>
Then I have a list of pages:
public pages: Page[] = [
{name: 'Home', link: '/home', icon: 'home'},
{name: 'Data', link: '/data', icon: 'format_list_bulleted'},
{name: 'Reports', link: '/reports', icon: 'bar_chart'},
];
When I click on a menu item, my page gets loaded correctly but routerLinkActive does not assign the class until I click anywhere on the screen. After that the class is there and I get the css on my menu to highlight the item. I am stuck on this and haven´t found anyone asking this. Could this be a bug or am I missing something?
Solution 1:[1]
Since your View is changing when you route the menu items, I suggest you to use Change Detector Ref to get the changes manually on your Component either; in the constructor or ngOnInit method.
constructor(changeDetectorRef: ChangeDetectorRef){
this.changeDetectorRef.detectChanges();}
// OR
ngOnInit(){
this.changeDetectorRef.detectChanges();
}
A question that mentions where should Change Detector to be used
Solution 2:[2]
Try !important in your css:
.is-active{
//your css with !important;
}
Reason: mat-list-item css is overshadowing the css defined inside is-active rule.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Halil Usanmaz |
Solution 2 |