Print Html template in Angular 2 (ng-print in Angular 2)


I want to print HTML template in angular 2. I had explored about this I got solution in angularjs 1 Print Html Template in Angularjs 1

Any suggestion would be appreciated

This question is tagged with javascript angularjs angular

~ Asked on 2016-12-29 11:58:08

The Best Answer is


That's how I've done it in angular2 (it is similar to that plunkered solution) In your HTML file:

<div id="print-section">
  // your html stuff that you want to print
<button (click)="print()">print</button>

and in your TS file :

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


You can also shortcut the path and use merely ngx-print library for less inconsistent coding (mixing JS and TS) and more out-of-the-box controllable and secured printing cases.

~ Answered on 2016-12-29 12:39:00


In case anyone else comes across this problem, if you have already laid the page out, I would recommend using media queries to set up your print page. You can then simply attach a print function to your html button and in your component call window.print();


<div class="doNotPrint">
    Header is here.

    all my beautiful print-related material is here.

<div class="doNotPrint">
    my footer is here.
    <button (click)="onPrint()">Print</button>




@media print{
  .doNotPrint{display:none !important;}

You can optionally also add other elements / sections you do not wish to print in the media query.

You can change the document margins and all in the print query as well, which makes it quite powerful. There are many articles online. Here is one that seems comprehensive: It also means you don't have to create a separate script to create a 'print version' of the page or use lots of javascript.

~ Answered on 2017-12-28 01:48:59

Most Viewed Questions: