How to switch off top-item selection for mat-nav-list inside mat-sidenav?

I’m using a fairly straightforward navigation list inside mat-sidenav, and whenever the sidenav is shown, it always highlights the top menu item:

<mat-sidenav-container class="example-container">
  <mat-sidenav #sidenav mode="over">
    <mat-nav-list>
      <mat-list-item *ngFor="let i of menuItems" [routerLink]="i.link">
        <span matListItemTitle>{{i.title}}</span>
      </mat-list-item>
    </mat-nav-list>
  </mat-sidenav>
  <mat-sidenav-content>
    side content
  </mat-sidenav-content>
</mat-sidenav-container>

enter image description here

I cannot fathom what causes it to highlight the top menu item every time, which makes no sense, as it does not correspond to the currently active URL or anything else.

How to get rid of this odd selection?

My CSS for the component:

.example-container {
  position: absolute;
  height: calc(100% - 64px);
  width: 100%;
}

mat-nav-list {
  min-width: 250px;
}

UPDATE

I have found out that if I remove [routerLink]="i.link", then it no longer highlights the top item. This tells me that there’s some issue mapping to the current root when the menu is activated. The top item is highlighted always, no matter which route is active.

And to make it even more clear, I have added routerLinkActive="active-link" just to show the abnormality when some route is selected…

mat-list-item.active-link {
  background-color: red;
}

Now if I activate route events, it looks like this:

enter image description here

So we do get the right class added to the active item, and the top item is just always highlighted 🙁


I’m using Angular v15.2.7, and latest Chrome.

>Solution :

as stated here:

Whether the drawer should focus the first focusable element automatically when opened. Defaults to false in when mode is set to side, otherwise defaults to true.

so, just add [autoFocus]="false" to your side-nav component:

<mat-sidenav #sidenav mode="over" autoFocus="false">

Leave a Reply