Search code examples
angularangular-routingangular-routerangular-routerlink

angular routing - navigate to same component with additional params without destroying the component


I have a routing setting like this

{
    path: '',
    component: BaseCmp,
    children: [
        { path: 'list', component: ListCmp },
        {
            path: 'list/:itemId',
            component: ListItemCmp,
        },
        {
            path: 'list/:itemId/:subNavItemId',
            component: ListItemCmp,
        }
    ]
}

I'm selecting an Item from the ListCmp and get navigated to for example 'list/123'

In the ListCmp Constructor/OnInit I'm fetching some data with the :itemId and it returns a list of SubNavItems, from which the id of the first SubNavItem should be added as params (for routerLinkActive to highlight and other fetching purposes).

constructor(route:ActivatedRoute, http:HttpClient, router:Router){
   let id = route.params.itemId
   http.get(.../id).subscribe(list => {
        // add id of first item of list to params
        this.router.navigate(['list', id, list[0].id, {replaceUrl:true}]
   })
} 

This will cause the destruction of the current ListItemCmp and instantiate a new ListItemCmp. How can I prevent that? I've tried the location.go() method but that won't trigger the routerLinkActive


Solution

  • Following my comment, your error was coming from the fact that your routes were siblings instead of parents : by routing away from the first sibling, you were destroying it to create the other sibling.

    With parent routes, the parent will stay (because it contains a router outlet and can't disappear), while the child will be appended to the parent, meaning the parent doesn't get destroyed.