I have a \"dashboard\" that loads configured elements. Dashboard template has this:
After some research, this is the solution i came up with (works in angular 4.0.0).
Load all the ViewContainerRef targets by id:
@ViewChildren('dynamic', {read: ViewContainerRef}) public widgetTargets: QueryList;
Then loop over them to get the target, create a factory for the component and call createComponent.
Also can use the component reference to subscribe or set other component properties.
ngAfterViewInit() {
const dashWidgetsConf = this.widgetConfigs();
const widgetComponents = this.widgetComponents();
for (let i = 0; i < this.widgetTargets.toArray().length; i++) {
let conf = dashWidgetsConf[i];
let component = widgetComponents[conf.id];
if(component) {
let target = this.widgetTargets.toArray()[i];
let widgetComponent = this.componentFactoryResolver.resolveComponentFactory(component);
let cmpRef: any = target.createComponent(widgetComponent);
if (cmpRef.instance.hasOwnProperty('title')) {
cmpRef.instance.title = conf.title;
}
}
}
}
The widgetComponents is a object {key: component} and widgetConfigs is where i store specific component info - like title, component id etc.
Then in template:
And the order of targets is the same as in my conf ( boxes is generated from it) - which is why i can loop through them in order and use i as index to get the correct conf and component.