Search code examples
angularangular7

How to use routerLink with two html's


So, I'm trying to makeing two seprate routerLinks with the same component but they have different html views. the problem is that it keeps giving me the Error of: "Error: Cannot match any routes".

This is the code I'm trying to implement:

{
    path: 'home', 
    component: HomeComponent,
}, 
{
   path: 'homeInfo/:id', 
   component: HomeComponent,
},

Can this be done? If yes how can I call 2 separate HTML's with the same controller using routerLinks...


Solution

  • Hope this will help you. Use your buttons as below.

    <button type="button" [routerLink]="['/homeInfo/',<your id>]" label="Home Info"></button>
    
    <button type="button" routerLink="/home/" label="Home"></button>
    

    In your Home component

    import { Component, OnInit } from '@angular/core';
    import { ActivatedRoute} from '@angular/router';
    
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.scss']
    })
    export class HomeComponent implements OnInit {
      constructor(
        private route: ActivatedRoute,
      ) {}
    
      title: string;
      id: number;
    
      //Based on these boolean values change HTML controls
      isHomeMode = false;
      isHomeInfoMode = false;
    
      msgs: any[];
    
      ngOnInit() {
        this.route.params.subscribe(params => {
          if (this.route.snapshot.url[0].path === 'home') {
            this.title = 'Home';
            this.isHomeMode = true;
          } else {
            this.title = 'Home Info';
            this.isHomeInfoMode = true;
            this.id = params.id;
          }
        });
      } 
    }
    

    StackBlitz :https://stackblitz.com/edit/angular-egkmls