Marko Čepo
Marko Čepo

Reputation: 315

Sibling components with router outlet

I ve started with angular and i just can't get my head around the Router, here is my problem ....

Lets assume i have a application structure like so ...

App structure

Now in Feature 'C' Component html is as follows ...

<feature-d-component></feature-d-component>
<feature-e-component></feature-e-component>

Each of those have an router-outlet, ie feature 'D' component and Feature 'E' component have the same html as follows

<router-outlet></router-outlet>

Can this be implemented? And if it can, could you give an route configuration example and also a example how would one route to this with routerLink?

Upvotes: 7

Views: 2654

Answers (1)

Narm
Narm

Reputation: 10864

Yes, what you described can be accomplished by using named router outlets.

For the purpose of demonstrating this I used the example app you provided in your image.

Example router config:

const appRoutes: Routes = [{   
    path: 'featureA',
      component: FeatureAComponent,
    }, {
      path: 'featureB',
      component: FeatureBComponent,
    },
    {
      path: 'featureC',
      component: FeatureCComponent,
      children: [
        { path: 'childE', component: EChildComponent, outlet: 'routeE' },
        { path: 'childD', component: DChildComponent, outlet: 'routeD' }
      ]
    },  { 
      path: '', 
      redirectTo: '/featureA',
      pathMatch: 'full'
   },
];

Your app.component.ts

@Component({
  selector: 'my-app',
  template: `
  <a [routerLink]="['featureA']">feature-a</a>
  <br>
  <a [routerLink]="['featureB']">feature-b</a>
  <br>
  <a [routerLink]="['featureC']">feature-c</a>
  <router-outlet></router-outlet>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {}

and your feature C component:

@Component({
  selector: 'feature-c',
  template: `
    <h1>Showing feature-c component</h1>
    <feature-d></feature-d>
    <feature-e></feature-e>
  `,
})
export class FeatureCComponent {
}

Now getting into the named router outlets. You mentioned you wanted to use routerLink, so that is the method I used in the demonstration. See feature-d:

@Component({
  selector: 'feature-d',
  template: `
    <h3>feature-d</h3>
    <a [routerLink]="[{ outlets: { routeD: ['childD'] } }]">Show child D</a>
    <router-outlet name="routeD"></router-outlet>
  `,
})
export class FeatureDComponent {
}

For simplicity Feature-e is implemented the same as feature-d. Attached is a live StackBlitz demo that I created so you can see it in action and play around with it to your liking.

Be warned I didn't do any beautification to the StackBlitz, so it looks pretty basic, but it gets the job done!

StackBlitz Demo

Upvotes: 8

Related Questions