无法从innerHTML获取动态数据 - Angular

时间:2018-01-10 03:16:41

标签: javascript html angular ionic-framework

我从我的视图或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>

2 个答案:

答案 0 :(得分:1)

您获得元素的旧内容,因为Angular的更改检测机制未在更改this.newData和您获取div内容的语句之间更新DOM。 HTML输出仅在当前执行周期后更新。

您可以使用多种技术强制进行变更检测(请参阅this answer)。其中一个是致电ChangeDetector.detectChanges()

顺便说一句,Angular在代码中访问DOM元素的方法是使用@ViewChild(varname)template reference variables,而不是调用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;
      ...
    }
  } 
}

答案 1 :(得分:1)

我建议使用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
    }

}

同时在how to perform DOM manipulation in Angular Components!

上查看这个非常相似的问题
相关问题