Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 printing a component

Tags:

angular

In plain JavaScript, you are able to print an element by getting the element ID, putting it in a new window, and using window.print().

What is the "Angular 2" way to do such a thing? I have gotten as far as getting a ViewChild of the component I wish to print, but I'm not sure how to access its html and subsequently print it, or if that's even what I'm supposed to do.

like image 842
Alex Palacios Avatar asked Feb 01 '17 16:02

Alex Palacios


1 Answers

If you need to print some custom HTML, this method doesn't need a new window.

ts:

    let control_Print;

    control_Print = document.getElementById('__printingFrame');

    let doc = control_Print.contentWindow.document;
    doc.open();
    doc.write("<div style='color:red;'>I WANT TO PRINT THIS, NOT THE CURRENT HTML</div>");
    doc.close();

    control_Print = control_Print.contentWindow;
    control_Print.focus();
    control_Print.print();

html:

<iframe title="Lets print" id="__printingFrame" style="width: 0; height: 0; border: 0"></iframe>
like image 142
Pablo Chvx Avatar answered Oct 11 '22 07:10

Pablo Chvx