首页 > 解决方案 > 使用 ngxPrint 在隐藏的 div 中打印内容时无法读取 null 的属性“getElementsByTagName”

问题描述

  <div *ngIf="isShown" id="print-section"> 
      <!--Your html stuff that you want to print-->
         
  </div>
        
  <button printTitle="MyTitle"  printSectionId="print-section" ngxPrint>print</button>
ngOnInit() { 
  this.isShown = false;
}

isShown如果我设置为false,为什么不能打印div内容。

标签: angularhiddengetelementsbytagname

解决方案


*ngIf是指令的语法糖[ngIf]。所以你的模板实际上会扩展到

<ng-template [ngIf]="isShown">
  <div id="print-section"> 
    <!--Your html stuff that you want to print-->
  </div>
</ng-template>

ng-template是更通用的 HTMLtemplate标记的 Angular 特定实现。因此,当您看到条件为假时,它div并没有像您说的那样隐藏,而是尚未呈现。因此,当您尝试时getElementsByTagName,该元素尚不可用。

作为一种解决方法,您可以使用 CSS 来隐藏元素,而不是*ngIf. 尝试以下

<div [style.display]="isShown ? 'block' : 'none'" id="print-section"> 
  <!--Your html stuff that you want to print-->
</div>

推荐阅读