html - 如何在 Angular 4 中使用 TS 打印頁面
我有一個網頁應用程式,而在某些頁面中我需要使用印表機列印頁面,但我有一個側邊欄,其他部分是用於一個元件的頁面,如何只列印這個元件而不列印側邊欄呢,我在 TS 中使用了這段程式碼。
print() {
window.print();
}
Html 代碼從這個開始。
div class="container">
//Here I have all the HTML source
</div>
答案#1
首先給那個元件分配一個 ID,然後:
const printContent = document.getElementById("componentID");
const WindowPrt = window.open('', '', 'left=0,top=0,width=900,height=900,toolbar=0,scrollbars=0,status=0');
WindowPrt.document.write(printContent.innerHTML);
WindowPrt.document.close();
WindowPrt.focus();
WindowPrt.print();
WindowPrt.close();
答案#2
你可以嘗試這個解決方案。
HTML 檔案
<div class="container" id="component1">
//Here I have all the HTML source
</div>
<div class="container" id="component2">
//Here I have all the HTML source
</div>
<button (click)="printComponent('component1')">Print</button>
ts 檔案
printComponent(cmpName) {
let printContents = document.getElementById(cmpName).innerHTML;
let originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
答案#3
在側邊欄元件的 scss 檔案或 css 檔案中……你可以使用媒體查詢在列印時隱藏它:
@media print {
:host {
display: none;
}
}
