The best option I found to solve this without getting into trouble with my styles was using a separate route for my printed output and load this route into an iframe.
My surrounding component is shown as a tab page.
@Component({
template: '<iframe id="printpage" name="printpage" *ngIf="printSrc" [src]="printSrc"></iframe>',
styleUrls: [ 'previewTab.scss' ]
})
export class PreviewTabPage {
printSrc: SafeUrl;
constructor(
private navParams: NavParams,
private sanitizer: DomSanitizer,
) {
// item to print is passed as url parameter
const itemId = navParams.get('itemId');
// set print page source for iframe in template
this.printSrc = this.sanitizer.bypassSecurityTrustResourceUrl(this.getAbsoluteUrl(itemId));
}
getAbsoluteUrl(itemId: string): string {
// some code to generate an absolute url for your item
return itemUrl;
}
}
The iframe just loads the print route that renders a print component in the app. In this page the print might be triggered after the view is fully initialized. Another way could be a print button on the parent component that triggers the print on the iframe by window.frames["printpage"].print();
.
@Component({
templateUrl: './print.html',
styleUrls: [ 'print.scss' ]
})
export class PrintPage implements AfterViewInit {
constructor() {}
ngAfterViewInit() {
// wait some time, so all images or other async data are loaded / rendered.
// print could be triggered after button press in the parent component as well.
setTimeout(() => {
// print current iframe
window.print();
}, 2000);
}
}