techie questie techie questie - 1 year ago 72
TypeScript Question

Angular2- Enable Print Functionality in the same window on click of a PRINT link

In my angular app, I have a component where in the template I have a print link on click of which i have to enable print functionality.I am trying something like this in my HTML-

<div>
<a href="#" (click)="print()">PRINT</a>
</div>


and in .ts file-

print(): void {
let printContents, popupWin;
printContents = document.getElementById('print-section').innerHTML;
popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
<html>
<head>
<title>Print tab</title>
<style>
//........Customized style.......
</style>
</head>
<body onload="window.print();window.close()">${printContents}</body>
</html>`
);
popupWin.document.close();
}


This works but it opens a new window for print. Is there anyw ay , I can have that in same window.
I also tried-

<a href="javascript:window.print();">Print</a>


But both of the above approach does not work. Any idea how can i get my page printed in angular2.

Answer Source

this works fine. We will be able to print the particular component However we need to add the styles inside tag in document.write function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download