component:
<div class="container" id="component1">
Content
</div>
<div class="container" id="component2">
other content
</div>
<button (click)="print('component1')">Print</button>
.ts file:
print(cmpName) {
let printContents = document.getElementById(cmpName).innerHTML;
let originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
after print the content of page is not clickable any solution to fix this issue. Thanks
2
Answers
Angular features, such as bindings and other things, require Angular compilation and other things in order to work.
When you directly change DOM using innerHTML, you are just replacing HTML content of your document, but other things (internal Angular mappings, bindings and other things) are not processed. So your (click) event listener and other things will not work since they are not connected to your newly set HTML content.
In order to use Angular features (in this case click listener), you should use Angular core functionalities. Generally, rarely you will have need to use direct DOM access (maybe in some rare cases) but in that case you will have to handle user interaction and other things let say "manually". That means that when you are manipulating with DOM directly, Angular does not now about that so Angular features are not working.
In your case, depends of your needs yo can do something such as:
You can control how printed area will be shown with css:
In this case, you can put * css selector inside this media block add hide everything and then in next selector show content that you want for the print and style it
Along with this you can show/hide some HTML content. But using Angular core features such as *ngIf or similar instead of direct innerHTML direct DOM access. But you have to now how Angular rendering works, so if you for example do something such as:
And in your print function:
This will not work since template will not be updated when window.print() is being executed because of the way how Angular handles rendering process (ZoneJs and other things).
After printing the content of the page using the print(), the entire content of the document.body replaced with the content you want to print. When you reset the document.body.innerHTML back to the original contents, the event handlers and other interactive elements are not restored.
there is another way to print the content of a specific element without affecting the entire page’s interactivity. Instead of manipulating the document.body.innerHTML, you can create a new window or iframe, populate it with the content you want to print, and then invoke the print functionality on that window or iframe.
To fix this issue you can try: