I want to create dynamic components and insert views of these components to a container.
I think this can be achieved by ViewContainerRef.
But I don\'t know,
I was searching for a solution to this problem as well.
The only way I was able to make it happen was to use an additional Component
import {Component, ViewContainerRef} from '@angular/core';
@Component({
selector: 'sw-view-container-ref',
template: ``
})
export class SwViewContainerRef {
private _viewContainerRef:ViewContainerRef;
constructor(viewContainerRef:ViewContainerRef) {
this._viewContainerRef = viewContainerRef;
}
get viewContainerRef():ViewContainerRef {
return this._viewContainerRef;
}
}
container.component.ts
import {Component, ComponentResolver, ViewContainerRef, AfterViewInit, ViewChild,Injector} from '@angular/core'
import {controlBoxComponent as controlBox} from './controlBox.component';
import {SwViewContainerRef} from "./sw-view-container-ref";
@Component({
selector: 'container',
template: 'container ',
directives: [SwViewContainerRef]
})
export class ContainerComponet implements AfterViewInit {
@ViewChild('swViewContainerRef', SwViewContainerRef) swViewChild:SwViewContainerRef;
ngAfterViewInit() {
this.desiredViewContainerRef = this.swViewChild.viewContainerRef;
var self = this;
this._cr.resolveComponent(controlBox).then((factory) => {
var componentRef = self.desiredViewContainerRef.createComponent(factory, null, self.injector, null);
componentRef.changeDetectorRef.detectChanges();
componentRef.onDestroy(()=> {
componentRef.changeDetectorRef.detach();
})
return componentRef;
});
}
public desiredViewContainerRef:ViewContainerRef;
constructor(private _cr: ComponentResolver, public injector:Injector) {
}
}
It should produce something similar to this.
container
controlBox
I'm not sure if my examples are clear or working, feel free to ask questions or make suggestions, I will try to answer and update my example.