要在Angular 8中打印HTML,可以使用@ViewChild
装饰器和Renderer2
来实现。
首先,确保你已经导入了ViewChild
和Renderer2
:
import { Component, ViewChild, ElementRef, Renderer2 } from '@angular/core';
然后,在组件类中添加以下代码:
@Component({
selector: 'app-print',
templateUrl: './print.component.html',
styleUrls: ['./print.component.css']
})
export class PrintComponent {
@ViewChild('printSection', {static: false}) printSection: ElementRef;
constructor(private renderer: Renderer2) { }
print(): void {
let printContents = this.printSection.nativeElement.innerHTML;
let originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
location.reload();
}
}
在模板文件中,添加一个带有#printSection
指令的元素,以便在组件中访问它:
现在,当用户点击"打印"按钮时,print()
方法将被调用。该方法首先获取printSection
元素的HTML内容,然后将其赋值给document.body.innerHTML
,以便将其打印出来。然后,它将原始的HTML内容重新赋值给document.body.innerHTML
,并重新加载页面,以便恢复原始状态。
请注意,由于安全原因,浏览器可能会阻止自动调用window.print()
。在某些浏览器中,用户必须手动点击打印按钮才能打印。