Search code examples
angularangular-materialangular-routing

How to Use Angular Routing from Child Component Using Angular Material


I am trying to set up routing on a toolbar component that I created. The toolbar component is called in my app.component and that's how it is added to the DOM. I have a menu with 3 buttons on that toolbar and I would like to make them route to different links.

I tried importing AngularRouting into my child component (toolbar) but I am not sure what I'm doing anymore lol.

./toolbar/toolbar.ts:

     <button mat-menu-item>
       <mat-icon>home</mat-icon>
       <span>Home</span>
     </button>
     <button mat-menu-item>
       <mat-icon>assignment</mat-icon>
       <span>About</span>
     </button>
     <button mat-menu-item>
       <mat-icon>help</mat-icon>
       <span>Help</span>
     </button>
   </mat-menu>

How do I setup routing on the child component that uses angular material?


Solution

  • This can be achieved in several ways.

    1. using routerLink

      <button routerLink='/home' mat-menu-item>
         <mat-icon>home</mat-icon>
         <span>Home</span>
       </button>
      

    2 using .ts file HTML

         <button (click)="navigateToHome()" mat-menu-item>
           <mat-icon>home</mat-icon>
           <span>Home</span>
         </button>
    

    TS

    constructor(private router:Router){}
    
    navigateToHome(){
    this.router.navigateByUrl('/home');
    }
    

    using Angular material doesn't change the way you navigate.

    Hope it helps!