52 lines
1.5 KiB
TypeScript
Raw Normal View History

//our root app component
import {Component, Compiler, ViewContainerRef, ViewChild, Input, ComponentRef, ComponentFactoryResolver, ChangeDetectorRef} from '@angular/core'
// Helper component to add dynamic components
@Component({
selector: 'component-loader',
template: `<div #target></div>`
})
export class ComponentLoader {
@ViewChild('target', { read: ViewContainerRef }) target;
@Input() type;
@Input() data;
cmpRef: ComponentRef<any>;
private isViewInitialized: boolean = false;
constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler,
private cdRef: ChangeDetectorRef) { }
updateComponent() {
if (!this.isViewInitialized) {
return;
}
if (this.cmpRef) {
this.cmpRef.destroy();
}
let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
this.cmpRef = this.target.createComponent(factory)
// to access the created instance use
// this.compRef.instance.someProperty = 'someValue';
// this.compRef.instance.someOutput.subscribe(val => doSomething());
this.cmpRef.instance.item = this.data;
this.cdRef.detectChanges();
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if (this.cmpRef) {
this.cmpRef.destroy();
}
}
}