0

UPDATE: I just had a look at the wrong Plunkr, this Plunkr seems to fit my usecase: http://plnkr.co/edit/GJTLrnQdRDBvZenX59PZ?p=preview

I want to dynamically create components, for example I have the following array:

[
  { data: {...}, type: 'hello' },
  { data: {...}, type: 'foo' }
  ...
]

and I want to iterate over the array and for each item I want to create the corresponding component, in this case for example hello maps to type HelloComponent and foo maps to type FooComponent.

This question is related to: Angular 2 dynamic tabs with user-click chosen components which accepted answer provides an plunkr: http://plnkr.co/edit/3dzkMVXe4AGSRhk11TXG?p=preview

The app.ts looks like:

 @Component({
 selector: 'my-app',
 providers: [],
 template: `
   <div>
     <h2>Dynamicaly Add Elements</h2>
     <button (click)="addItem()">add hello</button>
     <div #placeholder></div>
   </div>
 `,
 entryComponents: [HelloComponent, FooComponent]
})
export class App {
 @ViewChild('placeholder', {read: ViewContainerRef}) viewContainerRef;
 private componentFactory: ComponentFactory<any>;

 constructor(componentFactoryResolver: ComponentFactoryResolver, compiler: Compiler) {
   this.componentFactory = componentFactoryResolver.resolveComponentFactory(HelloComponent);
   //this.componentFactory = compiler.compileComponentSync(HelloComponent);
 }

 addItem () {
   this.viewContainerRef.createComponent(this.componentFactory, 0);
 }
}

There we dynamically create multiple components, but each of type HelloComponent. One possibility to add multiple different components would be to have a factory for each type and in addItem we would decide which factory to use but that seems extremely cumbersome.

Another option would be to use https://angular.io/docs/ts/latest/api/common/index/NgSwitch-directive.html (no dynamic component loading at all) but then we would manually have to maintain the switch cases.

Is there a more lean way to do that?

Community
  • 1
  • 1
B zum S
  • 258
  • 3
  • 10
  • 1
    The answer to the question you linked to seems to match your requirement quite well. The `dcl-wrapper` component adds the component you pass to its `type` input and not only `HelloComponent`. – Günter Zöchbauer Aug 22 '16 at 12:11
  • Yeah well, thanks, I missed the example with the `dcl-wrapper` :) – B zum S Aug 22 '16 at 12:15

0 Answers0