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?