Search code examples
angulartypescript

Angular 17 child routing


I am trying to use the child routing and I misunderstand something.

what is the different between

{path:'products',component:ProductsComponent,children:[{path:'details/:id',component:ProductDetailsComponent}]}

and

{path:'products',component:ProductsComponent},

{path:'products',children:[{path:'details/:id',component:ProductDetailsComponent}]},

because the first one the url was changed but didn't go to the ProductDetailsComponenton the other hand the 2nd one working fine the url changed and it goes to the ProductDetailsComponent

i was trying to use children routing in angular 17.


Solution

  • As far as I know, the second one can just be written as

    {path:'products',component:ProductsComponent},
    
    {path:'products/details/:id',component:ProductDetailsComponent},
    

    That what that configuration basically means,

    As to why the first one didn't work, you need to check the following.

    • ProductsComponent must contain a router-outlet inside the HTML, only then product details will get loaded inside it, basically, if there are children, they will get rendered in the component that you configure for that path (ProductsComponent), do this method, if you want to render the contents of product details inside product component, else go for the below routing

    • For another way of routing this, please try this.

    routing

     { 
          path:'products',
          children:[
              {path: '', component: ProductsComponent},
              {path: 'details/:id', component: ProductDetailsComponent},
          ],
     },
    

    Here products is the base path, when its just products then ProductsComponent will render, if its details/:id then ProductDetailsComponent will render, I am suggesting this since, its more readable!