使用ngxPrint在隐藏的div中打印int内容时,无法读取null的属性“ getElementsByTagName”

问题描述

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

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

解决方法

*ngIf是指令[ngIf]的语法糖。因此,您的模板实际上将扩展为

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

ng-template是更通用的HTML template标记的Angular特定实现。因此,如您所见,当条件为false时,div不会像您所说的那样被隐藏,而是尚未呈现。因此,当您尝试getElementsByTagName时,该元素尚不可用。

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

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

使用[hidden]="true"代替*ngIf="isShown",它将起作用。

app.component.html-

<div [hidden]="true" id="print-section"> 
  <h1>HELLO WORLD!!!</h1>
</div>
<button printTitle="MyTitle"  printSectionId="print-section" ngxPrint>print</button>

app.component.ts-

export class AppComponent { }

app.module.ts-

@NgModule({
declarations: [
    AppComponent
  ],imports: [
    BrowserModule,NgxPrintModule,AppRoutingModule
  ],providers: [],bootstrap: [AppComponent]
})
export class AppModule { }

package.json-

"dependencies": {
    "@angular/animations": "~10.1.3","@angular/common": "~10.1.3","@angular/compiler": "~10.1.3","@angular/core": "~10.1.3","@angular/forms": "~10.1.3","@angular/platform-browser": "~10.1.3","@angular/platform-browser-dynamic": "~10.1.3","@angular/router": "~10.1.3","ngx-print": "^1.2.0-beta.5","rxjs": "~6.6.0","tslib": "^2.0.0","zone.js": "~0.10.2"
  },"devDependencies": {
    "@angular-devkit/build-angular": "~0.1001.3","@angular/cli": "~10.1.3","@angular/compiler-cli": "~10.1.3","@types/node": "^12.11.1","@types/jasmine": "~3.5.0","@types/jasminewd2": "~2.0.3","codelyzer": "^6.0.0","jasmine-core": "~3.6.0","jasmine-spec-reporter": "~5.0.0","karma": "~5.0.0","karma-chrome-launcher": "~3.1.0","karma-coverage-istanbul-reporter": "~3.0.2","karma-jasmine": "~4.0.0","karma-jasmine-html-reporter": "^1.5.0","protractor": "~7.0.0","ts-node": "~8.3.0","tslint": "~6.1.0","typescript": "~4.0.2"
  }

输出-

ngx-print PDF