ViewContainerRef, ViewContainerRef .
2.3.0 attachView, ApplicationRef. , , :
export class HtmlContainer {
private attached: boolean = false;
private disposeFn: () => void;
constructor(
private hostElement: Element,
private appRef: ApplicationRef,
private componentFactoryResolver: ComponentFactoryResolver,
private injector: Injector) {
}
attach(component: Type<any>) : ComponentRef<any> {
if(this.attached) {
throw new Error('component has already been attached')
}
this.attached = true;
const childComponentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
let componentRef = childComponentFactory.create(this.injector);
this.appRef.attachView(componentRef.hostView);
this.disposeFn = () => {
this.appRef.detachView(componentRef.hostView);
componentRef.destroy();
};
this.hostElement.appendChild((componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0]);
return componentRef;
}
dispose() {
if(this.attached) {
this.disposeFn();
}
}
}
,
1)
this.componentFactoryResolver.resolveComponentFactory(component);
2) , compFactory.create
3) changeDetector (componentRef.hostView extends ChangeDetectorRef), appRef.attachView ( )
4) , , rootNode
this.hostElement.appendChild((componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0]);
:
@Component({
selector: 'my-app',
template: `<div id="myArea"></div> `,
entryComponents: [NewChildComponent]
})
export class AppComponent {
containers: HtmlContainer[] = [];
constructor(
private appRef: ApplicationRef,
private componentFactoryResolver: ComponentFactoryResolver,
private injector: Injector) {
}
ngOnInit() {
var myArea = document.getElementById('myArea');
var myRow = document.createElement("div");
myArea.appendChild(myRow);
this.addComponentToRow(NewChildComponent, myRow, 'test1');
this.addComponentToRow(NewChildComponent, myRow, 'test2');
}
addComponentToRow(component: Type<any>, row: HTMLElement, param: string) {
let container = new HtmlContainer(row, this.appRef, this.componentFactoryResolver, this.injector);
let componentRef = container.attach(component);
componentRef.instance.param1 = param;
this.containers.push(container);
}
ngOnDestroy() {
this.containers.forEach(container => container.dispose());
}
}
.