Download multiple components in one router with angular2 output

I have the following template for the root component of my angular2 application:

<main class="main"> <div class="main__container"> <div class="main__left-area"> <router-outlet name="left-zone"></router-outlet> </div> <div class="main__right-area"> <router-outlet name="right-zone"></router-outlet> </div> </div> </main> 

And the following routes:

 import { HomeSummaryComponent } from "../components/home-summary/home-summary.component" import { DataSummaryComponent } from "../components/data-summary/data-summary.component" import { AskSummaryComponent } from "../components/ask-summary/ask-summary.component" import { Routes } from "@angular/router" export const AppRoutes: Routes = [ { path: "", component: HomeSummaryComponent, outlet: "left-zone" }, { path: "", component: DataSummaryComponent, outlet: "right-zone" } ]; 

This really works very well, but I would like to be able to load more than one component in the "right zone" (and in the left as well as in fact). The idea would be:

 { path: "", components: [ DataSummaryComponent, AskSummaryComponent ], outlet: "right-zone" } 

Controllers will simply be added one by one. Currently supported? If not, is it possible to extend an existing RouterOutlet to do this?

thanks

+5
source share
1 answer

Only one component can be assigned using a route. What you can do is add a parent component consisting of DataSummaryComponent & AskSummaryComponent and configure it on the route.

Update:

As mentioned in the commentary, you can create a generic component that dynamically loads components using the configuration of data properties in the route,

Route configuration

 const appRoutes: Routes = [ { path: '', redirectTo: '/route1', pathMatch: 'full' }, { path: 'route1', component: MasterComponent, data: {puppets : [PuppetComponent1]} }, { path: 'route2', component: MasterComponent, data: {puppets : [PuppetComponent2, PuppetComponent3]}}, { path: 'route3', component: MasterComponent, data: {puppets : [PuppetComponent1, PuppetComponent2, PuppetComponent4]}} ]; 

Main component

 @Component({ template: `<h1>I am the Master of components</h1> <hr /> <div #puppetContainer></div> ` }) class MasterComponent { @ViewChild('puppetContainer', { read: ViewContainerRef }) puppetContainer: ViewContainerRef; constructor( private router: Router, private route: ActivatedRoute, private _componentFactoryResolver: ComponentFactoryResolver, private viewContainer: ViewContainerRef) { } ngOnInit(){ this.route.data .subscribe(data => { if(!!data && !!data.puppets && data.puppets.length > 0){ data.puppets.map(puppet => { let componentFactory = this._componentFactoryResolver.resolveComponentFactory(puppet); this.puppetContainer.createComponent(componentFactory); }); } }); } } 

Mark Plunker !!

Hope this helps!

+7
source

Source: https://habr.com/ru/post/1264847/


All Articles