Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular CDK Portal Detach from within Portal

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();
}
like image 867
Gethin Avatar asked Oct 17 '25 22:10

Gethin


1 Answers

As of portal API from Angular CDK:

this.errorMessagePortal.detach()

should do the trick!

like image 145
Davide Aresta Avatar answered Oct 20 '25 13:10

Davide Aresta