当源为空时,如何隐藏包含ng2pdfjsviewer的div?

问题描述 投票:0回答:2

我有一个使用ng2-pdfjs-viewer显示pdf的应用程序,当查看者的源为null时,我想隐藏包含查看者的div。我看过similar post,但这与我要完成的目标不同。这是我的代码:

component.ts

//onChange
onChange(event){
this.pdfViewerAutoLoad.pdfSrc = "";
}


//convert and display
@ViewChild('pdfViewerAutoLoad', {static:false}) pdfViewerAutoLoad;
pdf: ArrayBuffer;
_base64ToArrayBuffer(base64) {
  var binary_string = window.atob(base64);
  var len = binary_string.length;
  var bytes = new Uint8Array(len);
  for (var i = 0; i < len; i++) {
      bytes[i] = binary_string.charCodeAt(i);
  }
  return bytes.buffer;
}
b64toBlob = (base64, type = 'application/octet-stream') => 
fetch(`data:${type};base64,${base64}`).then(res => res.blob())

displayPDF(data:any){
this.b64toBlob(response.base64Result).then((data) =>{
this.pdfViewerAutoLoad.pdfSrc = data;
this.pdfViewerAutoLoad.refresh(); 
}

component.html

<div style="height:120vh; width:100%;" *ngIf="this.pdfViewerAutoLoad.pdfSrc !== null">
    <ng2-pdfjs-viewer  #pdfViewerAutoLoad></ng2-pdfjs-viewer>
</div>

[当我运行ngIf时,出现以下错误,“无法读取未定义的属性'pdfSrc'”。当查看器的源为空时,如何隐藏包含的div?

javascript angular
2个回答
0
投票

该错误指的是this.pdfViewerAutoLoad.pdfSrc,它在三个地方使用:两次在课堂上,一次作为模板。

该错误表示尚未启动this.pdfViewerAutoLoad.pdfSrc。在模板中,您可以在pdfSrc之前使用Elvis运算符(?。)对其进行修复。

<div style="height:120vh; width:100%;" *ngIf="pdfViewerAutoLoad?.pdfSrc !== null">

或类似这样:

<div style="height:120vh; width:100%;" *ngIf="pdfViewerAutoLoad && pdfViewerAutoLoad.pdfSrc !== null">

它的作用是,因为this.pdfViewerAutoLoad被错误地分配了值,所以Angular将等到该值输入后再继续执行该操作,这将解决该错误-如果该错误来自模板。

在组件类中,还需要启动this.pdfViewerAutoLoad属性,然后才能为它的pdfSrc属性分配值。

Tip

:访问模板中的类属性时,可以跳过this.

0
投票

看,您正在尝试使用自己的定义来隐藏某些内容。一旦元素变为可见,您的ViewChild

© www.soinside.com 2019 - 2024. All rights reserved.