Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4: Multiple (named) router-outlets in a child route: supported?

Tags:

I have a master-detail setup with also another section for "editing" a list item, all on 1 landing-route (in my sample app, the route is /stuff). The detail component is populated using the default router-outlet, and is located at /stuff/:index . I am trying to send the HTML to another router-outlet for the edit part via route /stuff/:index/edit, yet Angular cannot seem to recognize the route.

I went ahead and put a generalized version of the situation on Bitbucket:

https://bitbucket.org/squirrelsareduck/angularrouting/

Anyways, the general error is this:

Error: Cannot match any routes. URL Segment: 'stuff/1/edit'

Most-relevant parts of the code:

Routes definition:

const routes: Routes = [   { path: 'stuff', component: AComponent, children:[     { path: ':index', component: BComponent},     { path: ':index/edit', component: EditComponent, outlet:'editsection'}   ]} ]; 

a.component.html:

<ul>   <app-listitem     *ngFor="let a of items; let indexOI = index;"     [index]="indexOI"   [contentOI]="a">   </app-listitem> </ul> <router-outlet></router-outlet> <router-outlet name="editsection"></router-outlet> 

b.component.html:

<p>   Detail section works! {{ index }}   <button     type="button"     [routerLink]="['edit',{outlets:{editsection:'/stuff/:index/edit'}}]">     Edit   </button> </p> 

edit.component.html (less relevant, but important to recognize)

<p>   edit section works! </p> 
like image 290
squirrelsareduck Avatar asked Jun 24 '17 23:06

squirrelsareduck


People also ask

Can you have multiple router outlets in Angular?

You can have multiple router-outlet in same template by configuring your router and providing name to your router-outlet, you can achieve this as follows. Advantage of below approach is thats you can avoid dirty looking URL with it.

Can we use multiple router outlet?

Yes! We can use multiple router-outlets in same template by configuring our routers and simply add the router-outlet name. You can see in the example.

How many router outlets can be used in an Angular application?

There is no limit in angular but there are some best practices of using multiple place one in app.


1 Answers

Apply these changes in the b.component.html and it should work as expected.

<p>   Detail section works! {{ index }}  <button type="button"    [routerLink]="['/stuff',{outlets:{editsection:':index/edit'}}]">Edit</button> </p> 

For dynamic URL, using the routerLink, first, mention which route you want to go and then define the outlets and sub-routes as shown.

like image 118
Mani S Avatar answered Sep 28 '22 10:09

Mani S