kicior94
kicior94

Reputation: 53

routerLink directive does not work with mat-menu-item element

After clicking on mat-menu-item (Item1), nothing happens. I am sure that the router is configured properly, because it works if put anywhere else in the code. The weirdest thing is, that it was working, and after refreshing the browser it stopped working.

Nesting it inside nav element does not help

<mat-toolbar color = "primary" class = "subheader-menu mat-elevation-z4">
    <span class = "menu_button">
        <button mat-button [matMenuTriggerFor]="menu">Vehicles</button>
        <mat-menu #menu="matMenu">
            <button mat-menu-item [routerLink] = "['/example']">Item 1</button>
            <button mat-menu-item>Item 2</button>
        </mat-menu>
  </span>
</mat-toolbar>

I would like it to display the component that is bound to /example path.

Upvotes: 3

Views: 7907

Answers (3)

Walnussb&#228;r
Walnussb&#228;r

Reputation: 806

I experienced the same problem.

My problem was that the component that declared the menu was inside an Angular module that did not import RouterModule.

Try to import RouterModule in the module that declares the component which holds your menu. Then it should work.

Upvotes: 1

kicior94
kicior94

Reputation: 53

For some reason, neither solution worked. However, once I deleted the component and created it again, it started working once more.

Upvotes: 0

Sneha Pawar
Sneha Pawar

Reputation: 1127

Try doing routerLink as below

<button mat-menu-item routerLink="example" routerLinkActive="active"> Item 1</button>

OR

There is another solution for navigate to page, you can use click event for menu item

Your Html

 <button mat-menu-item (click)="navigateMenu('Item1')">Item 1</button>

TS file

import {Router} from '@angular/router';

constructor(private router: Router){}

navigateMenu(tag){
  if(tag === 'Item1'){
       this.router.navigate(['/example']);
      }
}

Upvotes: 4

Related Questions