Search code examples
angularangular-cdk

Angular CDK Portal, multiple Portals to one PortalOutlet?


So as the title states, is it actually possible using Angular CDK portals/portalOutlets to attach multiple portals to one PortalOutlet, I've been digging through the CDK source code and can't seem to find anything that indicates that it's possible.

Mainly drawing this conclusion on this code within portals.ts.

attach(portal: Portal<any>): any {
  if(!portal) {
    throwNullPortalError();
  }

    if(this.hasAttached()) {
  throwPortalAlreadyAttachedError();
}

if (this._isDisposed) {
  throwPortalOutletAlreadyDisposedError();
}

if (portal instanceof ComponentPortal) {
  this._attachedPortal = portal;
  return this.attachComponentPortal(portal);
} else if (portal instanceof TemplatePortal) {
  this._attachedPortal = portal;
  return this.attachTemplatePortal(portal);
}

I can obviously create multiple portalOutlets or lets say overlays in this scenario and attach a component portal to each overlay individually using the componentFactoryResolver, but again not really the scenario I'm after.


Solution

  • That's indeed not possible. What you could do is make one general container for your portals, then only attach/detach that container to the PortalOutlet depending if there are 1 or more portals to show.

    You will have to create your own attach view logic, but it's pretty straight forward using the viewContainerRef