Skip to content

Instantly share code, notes, and snippets.

@paveltretyakovru
Created March 13, 2019 22:50
Show Gist options
  • Save paveltretyakovru/78609ecf924a999e48d51db7fb959e30 to your computer and use it in GitHub Desktop.
Save paveltretyakovru/78609ecf924a999e48d51db7fb959e30 to your computer and use it in GitHub Desktop.
Creating Angular dynamic component with detaching data
export class ValidationMessageDirective implements AfterViewInit, OnDestroy {
private validationMessageComponent: ComponentRef<ValidationMessageComponent> = null;
ngAfterViewInit(): void {
let factory = this.componentFactoryResolver.resolveComponentFactory(this.vmComp);
this.ngOnDestroy();
this.validationMessageComponent = this.viewContainer.createComponent(factory, null, this.viewContainer.injector);
this.validationMessageComponent.changeDetectorRef.detectChanges();
}
ngOnDestroy(): void {
if (this.validationMessageComponent) {
this.validationMessageComponent.changeDetectorRef.detach();
//this.validationMessageComponent.destroy();
}
}
constructor(
private viewContainer: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver,
@Inject(ValidationMessageComponent) private vmComp: Type<ValidationMessageComponent>
) {}
/**
* @author Sergey Romanchuk
* @site https://stackoverflow.com/questions/42387348/angular2-dynamic-content-loading-throws-expression-changed-exception
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment