Created
March 13, 2019 22:50
-
-
Save paveltretyakovru/78609ecf924a999e48d51db7fb959e30 to your computer and use it in GitHub Desktop.
Creating Angular dynamic component with detaching data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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