55 lines
1.2 KiB
TypeScript
Raw Normal View History

2016-09-12 18:13:56 -04:00
import {ComponentFactory, Component, ComponentRef, Input, ViewContainerRef, ComponentResolver, ViewChild} from "@angular/core"
@Component({
selector: "dcl-wrapper",
template: `<div #target></div>`
})
export class DclWrapper
{
@ViewChild("target", { read: ViewContainerRef }) target;
@Input() type;
@Input() data;
cmpRef: ComponentRef<any>;
private isViewInitialized: boolean = false;
constructor(private resolver: ComponentResolver) { }
updateComponent()
{
if (!this.isViewInitialized)
{
return;
}
if (this.cmpRef)
{
this.cmpRef.destroy();
}
this.resolver.resolveComponent(this.type).then((factory: ComponentFactory<any>) =>
{
this.cmpRef = this.target.createComponent(factory);
//to access the created instance use
this.cmpRef.instance.item = this.data;
});
}
ngOnChanges()
{
this.updateComponent();
}
ngAfterViewInit()
{
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy()
{
if (this.cmpRef)
{
this.cmpRef.destroy();
}
}
}