0

I'm trying to implement a print funcion in my Angular application. This is what I've done so far:

typescript

print() {

    let printContents, popupWin;
    printContents = document.getElementById('print-section').innerHTML;
    popupWin = window.open();
    popupWin.document.open();
    popupWin.document.write(`
          <html>
            <head>
              <link rel="stylesheet" type="text/css" href="print.component.css">
            </head>
            <body onload="window.print();window.close()">${printContents}</body>
          </html>`
    );
    popupWin.document.close();
  }

html

<div id="print-section" hidden>
  <div class="red">Hello</div>
</div>

css

.red{
    color:red;
}

The print thing works, but it doesn't load the css. If I add a <style> tag inside the write() function it works. Why the css is not loaded? The .css file and the .ts file are in the same folder.

EDIT: thanks to @match suggestion I realized that the browser looks for the css file inside the current path, i.e. www.myurl.it/currentpage/print.component.css. Instead I want the browser looking for the file inside the sources folder, i.e. coponents/myComponent. Is there a way to do that?

4
  • What does the network section of your browser debugger show in relation to that file. No access? 404? Commented Feb 19, 2018 at 10:29
  • You're right, I didn't think to check. It shows 404. The path is wrong... Commented Feb 19, 2018 at 10:41
  • Does your component has relative path to its css file?. It should be something like styleUrls: ['./print.component.css']. Assuming that your .ts and .css are in same folder. Commented Feb 19, 2018 at 11:55
  • Yes @AmitChigadani it is correct. Commented Feb 20, 2018 at 13:51

1 Answer 1

2

Use

@media print {
      .red{
    color:red;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

yes I was going to say, use Media Queries. ( @Rakesh - it helps if you tell the questioner what your solution is using, so they can google for more information)
Thanks. If you meant to substitute my actual css with the media query it doesn't work, because the css is not loaded correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.