When trying to print a page on my Angular app, whether by using window.print() or pressing Ctrl + P, the print window opens but doesn't display the majority of the content on the page. After the first attempt is cancelled, a second attempt will render the page correctly in the print window, but reloading the app will revert back to not displaying the content correctly in the print window.
The content that is shown is several <div>
elements that are styled to serve as borders, as well as portions of parent components that are very far up the component tree (parts of the navbar component and the entire footer component, which are direct children of the app-component).
All content is correctly displayed on the page when this occurs, and is wrapped in an <ng-container *ngIf="!loading">
element. Loading is set to false when all component data is received.
The component is loaded like so:
ngOnInit() {
this.load();
}
load() {
// data is loaded from a service
this.loading = false;
setTimeout(window.print(), 500);
}
I've tried calling the window.print()
function in other lifecycle hooks (ngAfterContentInit, ngAfterViewInit) but with no noticeable change.
I've also tried setting longer timeouts, up to 20 seconds in length, but that also had no noticeable difference.
Edit
I tried logging document.ready
to the console before the print attempt and it logged as complete
Edit 2
It appears the problem stems from the stylesheet not being fully loaded when window.print()
is called. I have managed a bandaid fix by moving the CSS for the component to a separate file, as the main stylesheet is extremely large. Although the solution is not optimal, it has resolved the issue.
Is this a case of the DOM not being fully loaded and rendered when the window.print()
function is called? If so, how can I ensure that it is before trying to print the page?