我从我的视图或HTML中抓取动态数据,将它放在我的页面上,这样我就可以从所述数据中查看打印出来的内容。我必须使用这种方法,因为我正在创建自己的打印页面,其中包含这些动态数据。我使用的方法获取的是第一个初始值,而不是最新更新的DOM。如果我删除了.innerHTML,我就能够看到动态数据,但是不确定是否有一种方法可以不使用.innerHTML来获取该数据。
TS
click(data){
this.newData = data
let printContents, popupWin;
if(document.getElementById('print-section') != null){
printContents = document.getElementById('print-section').innerHTML;
popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
<html>
<head>
<title>Print tab</title>
<style>
//........Customized style.......
</style>
</head>
<body onload="window.print();window.close()">${printContents}</body>
</html>`
);
popupWin.document.close();
}
}HTML
<div id="print-section" style="display:none">
<div>
<p>{{newData.id}}</p>
</div>
</div>发布于 2018-01-10 03:29:39
您可以获得元素的旧内容,因为角的变化检测机制没有在更改到this.newData和获得div内容的语句之间更新DOM。只有在当前执行周期之后才会更新HTML输出。
您可以使用几种技术强制进行更改检测(请参阅这个答案)。其中之一是通过调用ChangeDetector.detectChanges()。
顺便说一下,在代码中访问DOM元素的方法是使用@ViewChild(varname)和模板参考变量,而不是调用document.getElementById。
<div #printSection style="display:none">
<div>
<p>{{newData.id}}</p>
</div>
</div>import { Component, ViewChild, ElementRef, ChangeDetectorRef } from '@angular/core';
export class MyComponent {
@ViewChild("printSection") printSectionRef: ElementRef;
constructor(private changeDetector: ChangeDetectorRef) {
}
click(data) {
this.newData = data
this.changeDetector.detectChanges(); // Trigger change detection
let printContents, popupWin;
if (this.printSectionRef && this.printSectionRef.nativeElement){
printContents = this.printSectionRef.nativeElement.innerHTML;
...
}
}
}发布于 2018-01-10 03:44:46
我使用ViewChild重新注释:我们视图中的子组件可以通过@ViewChild轻松地从父组件中访问。
<div id="print-section" #printContainer style="display:none">
<div>
<p>{{newData.id}}</p>
</div>
</div>构成部分:
export class MyComponent{
@ViewChild('printContainer') private printContainer: ElementRef; //import ElementRef
constructor() {
}
}单击方法:
click(data){
this.newData = data
let printContents, popupWin;
if(document.getElementById('print-section') != null){
printContents = this.printContainer.nativeElement.innerHTML;
// rest all remains same
}
}在如何在角度组件中执行DOM操作!上也要检查这个非常类似的问题
https://stackoverflow.com/questions/48179784
复制相似问题