问题
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
The window:
回答1:
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));
});
回答2:
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
回答3:
Another option is to use inline styling:
style="color:red;background-color:black;"
<window *ngIf="showPortal">
<h2 style="color:red;background-color:black;">Hello world from amother window!!</h2>
<div class="pin-bg">do you see pink ? do you?</div>
<button (click)="this.showPortal = false">Close me!</button>
</window>
来源:https://stackoverflow.com/questions/56920454/style-not-loaded-in-new-window