Load multiple component in the same router-outlet with angular2

被刻印的时光 ゝ 提交于 2019-12-01 17:02:43

Only one component can be assigned with a Route, What you may do is add a parent component consisting of DataSummaryComponent & AskSummaryComponent and configure it in the route.

Update:

As mentioned in comment you may create a generic component which loads components dynamically using data property configuration in 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]}}
];

Master 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);
                });
              }
           });
    }

}

Check this Plunker!!

Hope this helps!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!