Home > Mobile >  In Angular, with a portal opened in another window, how do I attach an overlayRef so it will use the
In Angular, with a portal opened in another window, how do I attach an overlayRef so it will use the

Time:11-28

In angular you have the CDK Portal library. From other sources on the internet I saw someone take a portal and open it in another window. It works. Then I wanted to see if I can make a dialog open in front of a portal window. This kind of works, because indeed the component is showing in the portal window, which is what I want, but the styles are not showing up, because I have a problem in attaching the overlay.

All I want to do, is open a dialog in front of a portal window (it would if it would just honor my styles in the login.component.scss). Now I KNOW you can use global styles. I could put the styles in the styles.css file, but I absolutely need to avoid doing this because of something I need to do later.

It's allot of code, so I included a stackblitz. The problem is attaching overlays somewhere.

Here is the problem code in the dialog service

open<T>(...){
  ...
  // Attach component portal to the overlay
  const comp = new ComponentPortal(component, null, injector);

  //This attaches the overlay to the main component (in our case app.component), 
  //but I don't want that, I want to attach to the window portal
  overlayRef.attach(comp);

  //THIS attaches to the portal, but doesn't use my styles in the login.component.scss
  portalWindow.externalPortalOutlet.attachComponentPortal(comp);

  ...
}

Again, I KNOW I can put styles in the styles.css file and it will "work", but that will give me problems later on down the road, so I must avoid that.

Ideas were pulled from John Woodruff website where I got I use his open method and dialog service since it ties well with my question

I also got this rudimentary portal window from rohyadev stack blitz

The basic module styles I simply got from W3Schools website. I simply slapped all of this together in order to ask my question.

CodePudding user response:

After doing some more research, I need to tell the portal window to append the styles of the new component we want in the portal window. So the problametic code is solved by doing this instead

open<T>{
  ...
  // Attach component portal to the overlay
  const comp = new ComponentPortal(component, null, injector);

  portalWindow.externalPortalOutlet.attachComponentPortal(comp);

  //This is the answer to the problem, manually attach the styles
  //to the portal window
  portalWindow.appendStyles();
  ...
}

So inside the portal window component we add that method like this

public appendStyles(){
  document.querySelectorAll('link, style').forEach(htmlElement => {
     this.externalWindow.document.head.appendChild(htmlElement.cloneNode(true));
  });
}

Updated stackblitz

  • Related