Tim Deschryver

Print CSS with Angular

Published | Modified

Recently, I had my first experience with the need to print out a webpage. I knew that this was possible by using a combination of the @page and the @media print CSS selectors.

But how can Angular help with this task, we asked ourselves. In this article, we'll take a look at the observations we made.

To get started with the print CSS, I found these two articles by Smashing Magazine helpful:

How can Angular help

If you're using Angular, there's a good chance that you're using a component-based architecture. We can use this architecture to our advantage. Instead of creating one big print stylesheet with some selectors, which becomes unmanageable complex when you have to support multiple printable pages. We can move some of the layout back to the components.

Adding print CSS to components has the same benefits as the styles to the component:

Adding a print CSS to a component

To change a component's look when printing a page, wrap the styles inside the @media print selector. Just like Angular's default styles, these styles are scoped to the current component.

This also means that child-component styles will overrule parent styles. In the below example, h1s from the parent component will be red, while the h1s from the child component will have the color blue.

Hiding entire components

Most of the specific print CSS we wrote was to hide components. To hide an entire Angular component, we can use the :host selector.

A separate print component

When the print version has a different layout, an option is to create a second component. This is especially useful if the printable component needs different data. This component will only be used for the print version.

A separate print stylesheet

Create a separate stylesheet where the print styles live. This leads to a clear separation, to clearly distinguish the application's layout and the print layout,

Adding a print button

It's possible to print a page with JavaScript, for users this is easier compared to printing out the page via the browser's interface or via a shortcut.

DevTools print media type

The developer experience while testing out the prints, was not so enjoyable because we had to manually trigger a print to see the page. That was until we found out that browsers can emulate the print view. The feedback loop was shorter as the page would just refresh when we made a change, just like we're used to.

In Chrome via More Tools > Rendering > Emulate CSS media type

Emulate CSS media type in chrome

In Firefox this view can be toggled the Rules pane in the DevTools

Emulate CSS media type in firefox

Please consider supporting me if have you enjoyed this post and found it useful:

Buy Me A Coffee PayPal logo
Support the blog Share on Twitter Discuss on Twitter Edit on GitHub