Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style not loaded in new window

I reproduced the problem with minimal code on this Stackblitz .

I made part of my component open on a new window BUT it should still be able to interact with my main app. I used DomPortalHost to achieve that. The interaction works successfully but the style are not loaded into the new window.

How do I force the new window to match the style of the main app?

The main app

enter image description here

The window:

enter image description here

like image 318
TSR Avatar asked Jul 07 '19 08:07

TSR


2 Answers

Your modal window does not contain the CSS styles of the parent window. So you have to clone them yourself to new window as cdk portal is not supposed to do that.

Add the following step in your ngOnInit method:

// STEP 5.1: clone stylesheets and style tags to external window
document.querySelectorAll('link, style').forEach(htmlElement => {
  this.externalWindow.document.head.appendChild(htmlElement.cloneNode(true));
});
like image 77
Munim Munna Avatar answered Nov 03 '22 00:11

Munim Munna


1) create one css file in assets folder that contain common css both for component and external window and give css file path in index.html or in angular.json so that component loads this css.

index.html

<script>document.write('<link href="/assets/css/appstyles.css?v=' + Date.now() + '" rel="stylesheet" />');</script>

assets/css/appstyles.css

.pin-bg {
    background: pink;
    width: 255px;
    height: 20px;
}

2) give css path for external window as:-

this.externalWindow.document.write('<html><head><link rel="stylesheet" type="text/css" href="assets/css/appstyles.css"></head><body>');

window.component.ts

ngOnInit(){

// STEP 4: create an external window
 this.externalWindow = window.open('', '', 'width=600,height=400,left=200,top=200');
 this.externalWindow.document.write('<html><head><style type="text/css">.pin-bg { background: pink; width:255px; height: 20px;}</style></head><body>');
}

or,

ngOnInit(){
// STEP 4: create an external window
 this.externalWindow = window.open('', '', 'width=600,height=400,left=200,top=200');
 this.externalWindow.document.write('<html><head><link rel="stylesheet" type="text/css" href="assets/css/appstyles.css"></head><body>');
  }

assets/css/appstyles.css

.pin-bg {
    background: pink;
    width: 255px;
    height: 20px;
}

Stackblitz link:- https://stackblitz.com/edit/angular-open-window-tbd3a4?file=src/app/window.component.ts

like image 37
Manzer Avatar answered Nov 03 '22 00:11

Manzer