kr_v
kr_v

Reputation: 139

Highlight current route item without clicking it

I have menu items that can be clicked and takes to different routes. When route is changed by clicking on item, it stays highlighted. For example, click on Home, takes to url.com/home and Home button stays highlighted. But if I go directly to url.com/home, the Home button is not highlighted.

<li nz-menu-item routerLink="/home" routerLinkActive="active">
   <span title><i nz-icon type="home"></i>Home</span>
 </li>   
<li nz-menu-item routerLink="/about" routerLinkActive="active">
   <span title><i nz-icon type="info-circle"></i>About</span>
 </li>

How to change it that item is highlighted any time when the specific route is open?

Upvotes: 0

Views: 2093

Answers (3)

Mark Heimer
Mark Heimer

Reputation: 49

if you are using ng-zorro-antd-package in version 10 there is a property called [nzMatchRouter] on nz-menu-items which sets nzSelected according to the routerlink

https://ng.ant.design/components/menu/en#%5Bnz-menu-item%5D

With this you dont need any additional typescript as @kounex mentioned

<li nz-menu-item routerLink="/home" [nzMatchRouter]="true" routerLinkActive="active">
   <span title><i nz-icon type="home"></i>Home</span>
 </li>   
<li nz-menu-item routerLink="/about" [nzMatchRouter]="true" routerLinkActive="active">
   <span title><i nz-icon type="info-circle"></i>About</span>
 </li>

Upvotes: 3

kounex
kounex

Reputation: 1715

Since you are using ng-zorro you can use the nzSelected property for your li tag to determine if it should be highlighted or not. Inject Router in your components typescript and check if the current url is matching the menu-item

HTML

<li nz-menu-item [nzSelected]="this.isSelected('/home')" routerLink="/home" routerLinkActive="active">
   <span title><i nz-icon type="home"></i>Home</span>
 </li>   
<li nz-menu-item [nzSelected]="this.isSelected('/about')" routerLink="/about" routerLinkActive="active">
   <span title><i nz-icon type="info-circle"></i>About</span>
 </li>

TS

constructor(private router: Router)
...

isSelected(route: string): boolean {
    return route === this.router.url;
}

Upvotes: 3

user4676340
user4676340

Reputation:

That's because you're not supposed to touch the URL yourself. When you do so, you do not send routing events to Angular.

Try navigating twice to the URL, this will reload your page : with this, your app reloads, effectively sending routing events.

If you wish to implement the desired behavior, you will have to listen to URL changes and reload your actual route.

Upvotes: 1

Related Questions