Angular dynamic route outlets not working

40 Views Asked by At

I have a simple route config

const appRoutes: Route[] = [
  {
    path: 'route',
    outlet: 'outlet',
    component: TestComponent,
  }
];

What I want to do is each time create router outlet button is clicked, update current app route config with a new route similar to existing route above but with different outlet name. Create a new route outlet with name attribute set to outlet-1

 const appRoutes: Route[] = [
      {
        path: 'route',
        outlet: 'outlet',
        component: TestComponent,
      },
      {
        path: 'route',
        outlet: 'outlet-1',
        component: TestComponent,
      }
    ];

<router-outlet name="outlet-1"/>

When I navigate to this new route outlet, TestComponent should be rendered below respective outlet.

this.router.navigate([{ outlets: { ['outlet-1']: ['route'] } } ]);

I am able to achieve what I described above but test component is created multiple times.

Here is a stackblitz

open brower console

click on the button once -> test component constructor. logged once.

click on the button 2nd time -> test component constructor. logged 2 times.

click on the button 3rd time -> test component constructor. logged 3 times.

etc..

Ideally message should be logged once per button click. what's the issue?

2

There are 2 best solutions below

1
Martin Araujo On BEST ANSWER

After redefining a router via resetConfig(), Angular re-renders all the components into the routes again.

0
Ravi Teja On

To solve it use

this.router.config.push(newRoute);

instead of

this.router.resetConfig([...this.router.config, newRoute]);.

Here is the updated Stackblitz

Also, if route contains child routes then parent routes component (in this case TestComponent) must contain router-outlet in its template else child routes will not render.