Skip to content

Instantly share code, notes, and snippets.

@ngohungphuc
Created August 22, 2019 14:43
Show Gist options
  • Select an option

  • Save ngohungphuc/6d4c682d7fc549a59a5c349441cf2672 to your computer and use it in GitHub Desktop.

Select an option

Save ngohungphuc/6d4c682d7fc549a59a5c349441cf2672 to your computer and use it in GitHub Desktop.
import {
ComponentFactoryResolver,
Injectable,
ComponentRef
} from "@angular/core";
@Injectable()
export class ComponentFactoryService {
private componentRef: ComponentRef<any>;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
createComponent(
componentInstance: any,
viewContainer: any
): ComponentRef<any> {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
componentInstance
);
const viewContainerRef = viewContainer.viewContainerRef;
viewContainerRef.clear();
this.componentRef = viewContainerRef.createComponent(componentFactory);
return this.componentRef;
}
destroyComponent() {
if (this.componentRef) {
this.componentRef.destroy();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment