In Angular Material menu, how can I highlight (e.g. change its bg color) the triggering button (i.e. with the [matMenuTriggerFor] attribute) for a menu while the menu has an menu item which is highlighted because of routerLink matching:
<button mat-button [matMenuTriggerFor]="animals">Animal index</button>
<mat-menu #animals="matMenu">
<button mat-menu-item routerLink="/vertebrates" routerLinkActive="active-menu-item">Vertebrates</button>
<button mat-menu-item routerLink="/invertebrates" routerLinkActive="active-menu-item">Invertebrates</button>
</mat-menu>
Is there any Angular directive available for this purpose or any CSS trick can do?
Mat menu does not have any inbuild directives to achieve this, but you can use isActiveChange event to check if any of the items in the option is active
<button mat-button [matMenuTriggerFor]="animals" [ngClass]="{'is-option-active': isOptionActive}">Animal index</button>
<mat-menu #animals="matMenu">
<button mat-menu-item routerLink="/vertebrates" routerLinkActive="active-menu-item" (isActiveChange)="onRouterLinkActive($event)">Vertebrates</button>
<button mat-menu-item routerLink="/invertebrates" routerLinkActive="active-menu-item" (isActiveChange)="onRouterLinkActive($event)">Invertebrates</button>
</mat-menu>
.is-option-active {
// add the styles for highlighting here
}
isOptionActive = false;
constructor(private router: Router) {
this.router.events.subscribe((ev) => {
if (ev instanceof NavigationEnd) {
this.isOptionActive = false;
}
});
}
onRouterLinkActive(ev) {
if (this.isOptionActive === false && ev === true) {
this.isOptionActive = true;
}
}