I'm using Angular CDK's portal to create an error message component that needs to be rendered in the body (hence using portal) on top of everything else.
It's working perfectly, though on the error message itself I need to be able to close it from within the component.
I am using a service to setup the portal and open/hide the message. The issue is that I can't call the close method from within the error message component itself because then I have a circular dependency and it all breaks down.
I know with the CDK's overlay you can reference it from within its component, is there any way to do the same for portal so I can detach the portal from within the error message component?
Thanks.
Here's the service code
private errorMessagePortal: ComponentPortal<ErrorMessageComponent>;
private bodyPortalHost: DomPortalHost;
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private appRef: ApplicationRef,
private injector: Injector
) {
this.errorMessagePortal = new ComponentPortal(ErrorMessageComponent);
this.bodyPortalHost = new DomPortalHost(document.body, this.componentFactoryResolver, this.appRef, this.injector);
}
// show error message
showErrorMessage(errorMessage: ErrorMessage) {this.bodyPortalHost.attachComponentPortal(this.errorMessagePortal).instance.errorMessage = errorMessage;
}
closeErrorMessage() {
this.bodyPortalHost.detach();
}
As of portal API from Angular CDK:
this.errorMessagePortal.detach()
should do the trick!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With