Theme not being rendered properly following the generation of a dynamic component in Angular

I am currently working on an Angular 9 application and I have successfully implemented a print functionality by creating components dynamically. However, I have encountered an issue where the CSS properties defined in the print-report.component.scss file are not being applied when the print window opens.

print.service.ts

@Injectable()
export class PrintService {

    constructor(
        private componentFactoryResolver: ComponentFactoryResolver,
        private injector: Injector
    ) { }

    showDialog(component) {
        const factory = this.componentFactoryResolver.resolveComponentFactory(component);
        
        const dialogComponentRef = factory.create(this.injector);
        dialogComponentRef.instance.title = 'Print page';
        
        dialogComponentRef.changeDetectorRef.detectChanges();

        //fetch the root DOM element of ModalComponent
        const domElement = (dialogComponentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
        
        const WindowPrt = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
        WindowPrt.document.write(domElement.innerHTML);
        WindowPrt.document.close();
        WindowPrt.focus();
        WindowPrt.print();
        WindowPrt.close();
    }

}

print-report.component.ts

@Component({
    selector: 'app-print-report',
    templateUrl: './print-report.component.html',
    styleUrls: ['./print-report.component.scss'],
    encapsulation: ViewEncapsulation.None
})
export class PrintReportComponent {

    @Input() title: string;    
}

print-report.component.html

<div class="name">{{title}}</div>

print-report.component.scss

.name { // the styles below are not being applied correctly when print window opens
   color: red;
   font-weight: bold;
}

my-custom-component.ts

constructor(private printService: PrintService){}

onButtonClick(){
    this.printService.showDialog(PrintReportComponent);
}

Answer №1

One issue that needs to be addressed is the fact that only the HTML content is being added to the new document here. A more efficient approach would involve:

displayDialog(component) {
    const factory = this.componentFactoryResolver.resolveComponentFactory(component);
    
    const dialogComponentRef = factory.create(this.injector);
    
    dialogComponentRef.changeDetectorRef.detectChanges();

    // Obtain the root element of ModalComponent
    const domElement = (dialogComponentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
    
    const newWindow = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
    newWindow.document.head.innerHTML = document.head.innerHTML;
    newWindow.document.body.innerHTML = domElement.outerHTML;
    newWindow.document.close();
    newWindow.focus();
    newWindow.print();
}

A more effective solution would involve extracting the component's CSS file and adding it to the head.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What method is used to initialize the variables in this JavaScript snippet, and what other inquiries are posed?

As a backend developer, I'm looking to understand this JavaScript snippet. While I grasp some parts and have added comments where I am clear, there are still sections that leave me with bold questions. function transformData (output) { // QUESTIO ...

How can you send Django context data to a JavaScript variable?

I need to send each value of the {{ i.nsn }} to the ajax script one by one. {% for i in dibbs %} <p>{{ i.nsn }}</p> {% endfor %} Instead of repeating the ajax script, I want it to function with a single click. <script> var nsn = " ...

Error encountered: Provider '$rootScopeProvider' is not recognized - check for typos in the syntax

I am encountering an issue with the templateUrl in AngularJS. When I input this code into my editor and execute it, everything works flawlessly: HTML: <!DOCTYPE html> <html lang= "en"> <head> <meta charset="UTF-8" /> < ...

Unique style pattern for parent links with both nested and non-nested elements

I am in the process of designing a website and I have a specific vision for how I want my links to appear, but I am unsure of how to achieve it. Here is the desired outcome: a red link a green link a red link a green link … Below is the HTM ...

An error persists in PhpStorm inspection regarding the absence of AppComponent declaration in an Angular module

After creating a new Angular application, I am encountering the issue of getting the error message "X is not declared in any Angular module" on every component, including the automatically generated AppComponent. Despite having the latest version of the An ...

Troubleshooting AngularJS ng-route and Three.js crashes and glitches: A comprehensive guide

I am currently working on a website that utilizes angularjs along with the ng-route directive for navigation between different views. The site also incorporates Three.js for WebGL rendering on canvas. However, I am encountering difficulties as the applicat ...

Learn how to send dynamic data to another HTML element using Ajax's success function

I received a successful ajax response from one HTML file, but I'm struggling to dynamically set the data from this response to another HTML file. Can anyone help me with this issue? Here is the code snippet from my ajax report: success: function( ...

What is the best way to transform an Object into an Array?

[ { id: '5b3a223296fb381a29cf6fd9', number: 1, name: 'Tablet White EliteBook Revolve 810 G2', dprice: '0', image: '' } ] This message is generated by the angular application. Upon inspecting its type, it was identi ...

Sending a JSON object as a map through AJAX to an MVC controller

I am looking to send a map (dictionary) to the MVC controller along with a string parameter. var reportName= 'ReportName'; var FilterValues = new Map([ [0, "value1"], [1, "value2"], [2, "value3"], ]); var model = { reportName: reportName, ...

What causes a delay in the start of a child process in Node.js?

I am in the process of developing a global node command line program that can execute any console command I provide it with in a new console window, whether on a Windows or Unix system. The goal is for the program to exit after it spawns its process so tha ...

Using jQuery, how can you make fixed elements fade as the page scrolls?

How can I make a fixed element, such as a corner ad or notice, fade when the page is scrolled down to a certain point? What would be the most effective method for determining this point: using pixels, percentage, or another way? And how can I implement th ...

It is important for the button size to remain consistent, regardless of any increase in text content

My goal was to keep the button size fixed, even as the text on it grows. This is the current code I am using: .button { border: none; color: white; padding: 10px 50px; text-align: center; text-decoration: none; display: inline-block; font ...

What do the letters enclosed in brackets signify?

I am currently working with a library known as Monet.js, and within the documentation, there are descriptions that look like this: Maybe[A].map(fn: A => B) : Maybe[B] I am unsure of what the letters inside the brackets stand for. Is there anyone who c ...

What is the best way to search a map object that serves as the document ID in Firebase?

I am attempting to retrieve all fieldnames within the payload > (random doc id) objects. https://i.sstatic.net/y9703.png At this moment, my approach involves fetching other collections using the following code: async fetchPage() { const query = fir ...

Display a loading screen while transitioning between routes in Angular 2

Is there a way to implement a loading screen for route changes in Angular 2? ...

How do I integrate a button into my grey navigation bar using tailwindcss in REACT?

Is it possible to integrate the - button into the gray bar? I am encountering an issue where my blue button extends beyond the borders of the gray bar in the image provided. export default function App() { ... return ( <div className="text-md fon ...

Unable to connect to localhost nodejs server from Windows browser when using WSL2

My computer runs on Windows 10 and has the Linux (Ubuntu-20.04) subsystem using WSL2. I've successfully initiated a frontend project (vue project) and running npm run serve works as expected with the application running on localhost:8080. However, whe ...

The error message "TranslateService not found" seems to be linked to the npm installation process

Encountering an issue with my Angular+Webpack+JHipster+yarn project where a particular error keeps reappearing despite deleting `node_modules` and running 'npm install`. The error seems to be related to the TranslateService provided by a library, not ...

Refresh the page only when on the initial page of the pagination

I've been utilizing this jQuery code with AJAX for pagination purposes. Currently, I am fetching data from a PHP file that displays limited information. Here is the index file snippet: <script type="text/javascript"> $(document).ready(fun ...

Converting a JavaScript function to work in TypeScript: a step-by-step guide

When writing it like this, using the this keyword is not possible. LoadDrawing(drawing_name) { this.glg.LoadWidgetFromURL(drawing_name, null, this.LoadCB,drawing_name); } LoadCB(drawing, drawing_name) { if (drawing == null) { return; ...