I have the following code in my component.ts file on one particular page, because that page needs to use it's own css for when the page is printed:
@Component({
selector: "dashboard",
templateUrl: "./dashboard.component.html",
styleUrls: ["./dashboard.component.scss"],
encapsulation: ViewEncapsulation.None
})
However, when i navigate off that page, i want the encapsulation to go back to normal for everywhere else. Is there a way to do this?
Or is there a way to only set the encapsulation when the print button is clicked? And then when closed it goes back to normal?
If I navigate away from this page and refresh, then the other pages go back to normal, but I don't want to have to refresh.
EDIT
I had to add in the encapsulation in order to get the page to print landscape using this code in the scss file:
@media print {
@page {
size: landscape
}
.no-print,
.no-print * {
display: none !important;
}
body {
-webkit-print-color-adjust: exact;
}
canvas {
max-width: 100%;
height: auto;
}
.printClass {
display: inline-block;
}
}
Otherwise, it would just take the global scss and print portrait every time.
Yes. In this example we use ngx-print
. This is a library you can see on GitHub . You do not use it, but it is using the right way and it is very straight forward.
npm install ngx-print
Using
<!--
1)- Add an ID here
-->
<div id="print-section">
<!--Your html stuff that you want to print-->
</div>
<!--
2)- Add the directive name in your button (ngxPrint),
3)- Affect your ID to printSectionId
-->
<button printSectionId="print-section" ngxPrint>print</button>
You can set things in css. Here is a sample:
Here is the heart of it:
public print(): void {
let printContents, popupWin, styles = '', links = '';
const baseTag = this.getElementTag('base');
if(this.useExistingCss) {
styles = this.getElementTag('style');
links = this.getElementTag('link');
}
printContents = this.getHtmlContents();
popupWin = window.open("", "_blank", "top=0,left=0,height=auto,width=auto");
popupWin.document.open();
popupWin.document.write(`
<html>
<head>
<title>${this.printTitle ? this.printTitle : ""}</title>
${baseTag}
${this.returnStyleValues()}
${this.returnStyleSheetLinkTags()}
${styles}
${links}
</head>
<body>
${printContents}
<script defer>
function triggerPrint(event) {
window.removeEventListener('load', triggerPrint, false);
${this.previewOnly ? '' : `setTimeout(function() {
closeWindow(window.print());
}, ${this.printDelay});`}
}
function closeWindow(){
window.close();
}
window.addEventListener('load', triggerPrint, false);
</script>
</body>
</html>`);
popupWin.document.close();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.