Home > Software design >  Angular loading component based on route parameter
Angular loading component based on route parameter

Time:01-05

I want to load component based on URL parameter when the user clicks on a link in the home component. For exmaple user is at "/home" which have a list of links

Link 1 Link 2

When the user clicks on Link 1 or 2, I want to load the details component and the url should be '/home/details/1' the "1" in the end is a route parameter.

Same thing happens when user clicks on Link 2, same details component is loaded but the parameter is "2" and url changes to '/home/details/2'

I have tried the following in routing module, the url changes but details component does not loads and no error is reported in the console.

const routes: Routes = [
  {
     path:'',
     component:HomeComponent,
     children:[
      {
        path:':id',
        component:DetailsComponent
      }]
   }
]

And the anchor tags are:

<a [routerLink]="[1]">Link 1</a>
<a [routerLink]="[2]">Link 2</a>

CodePudding user response:

Try <a [routerLink]="['/home',2]">Link 2</a> and

const routes: Routes = [
  {
     path:'home',
     component:HomeComponent,
     children:[
      {
        path:':id',
        component:DetailsComponent
      }]
   }
]

Also you should generate your pages with the following command:

ng g module detail --module person --route {personid}/detail

CodePudding user response:

If you want to redirect to certain pages you can always use this

In RouteModule
    const routes: Routes = [
      {
         path:'Home',
         component:HomeComponent,
         children:[
          {
            path:':id',
            component:DetailsComponent
          }]
       }
    ]

    In Html

    <a [routerLink] = ['/Home','1'] >Link 1</a>
     <a [routerLink] = ['/Home','2']>Link 2</a>
     
  

  •  Tags:  
  • Related