andyrue
andyrue

Reputation: 952

How to use routerLink relative to its parent with a named outlet?

Angular 13.2.2

I have a named route that is nested under another named route with a module that is lazy loaded. The routes look like this.

app.routing

{
    path: 'active',
    outlet: 'editor',
    loadChildren: () => import('./editor/editor.module').then(m => m.EditorModule),
},

editor.routing

{
    path: '',
    component: EditorComponent,
    children: [
      {
        path: 'a',
        outlet: 'subbar',
        component: AComponent
      },
      {
        path: 'b',
        outlet: 'subbar',
        component: BComponent
      }
    ]
}

The links are being generated dynamically so I am setting my routerLinks programmatically like this:

this.url = [ { outlets: { 'subbar': button.url } } ] where button.url is either a or b. So I end up with two buttons that have links to a and b.

and then

[routerLink]='url'

First I navigate to (editor:active), and my button links look like http://localhost:4200/home(editor:active/(subbar:a)) and same for b. This is correct.

The first time I go to one of the links, it works correctly and navigates to

(editor:active/(subbar:a))

But then the link to b shows http://localhost:4200/home(editor:active/(subbar:/(a//subbar:b))) which of course is a route that doesn't exist.

If I change things to use router.navigate(this.url, { relativeTo: this.route.parent }) then it works. What is interesting is that everything was fine without lazy loading, but when I switched to lazy loading the editor module, it introduced this problem.

I have tried adding '..' and '../' to the routerLink but it makes no positive difference. How can I replicate what router.navigate is doing with the relativeTo attribute on a routerLink?

Upvotes: 3

Views: 1396

Answers (1)

andyrue
andyrue

Reputation: 952

To get this to work, I had to change how the routing config was set up, but I think it partially defeats the point of lazy loading, just not sure how much.

Change the child routes file to be like this, removing the parent component and leaving the children.

// editor.routing
routes = [
      {
        path: 'a',
        outlet: 'subbar',
        component: AComponent
      },
      {
        path: 'b',
        outlet: 'subbar',
        component: BComponent
      }
    ]
}

And the main route to be like this.

//app.routing
{
  path: 'active',
  outlet: 'editor',
  loadChildren: () =>
    import('./editor/editor.module').then((m) => m.EditorModule),
  component: EditorComponent, // <- Add Component Here
}

Upvotes: 2

Related Questions