0

I have an application that uses ng2-pdfjs-viewer to display a pdf and I would like to hide the div containing the viewer when the viewer's source is null. I have looked at a similar post, however this is not the same as what I am trying to accomplish. Here is my code:

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>

When I run the ngIf I get the following error, "Cannot read property 'pdfSrc' of undefined". How do I hide the containing div when the viewer's source is empty?

Skullomania
  • 2,225
  • 2
  • 29
  • 65

2 Answers2

0

That error refers to this.pdfViewerAutoLoad.pdfSrc, which is used in three places: twice in class and once it the template.

The error means that this.pdfViewerAutoLoad.pdfSrc hasn't been initiated. In the template, you can fix it with the elvis operator (?.) before pdfSrc.

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

or like this:

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

What it does is, because this.pdfViewerAutoLoad is being assigned values asncroneously, Angular will wait until the value comes in before proceeding wit that, and that will resolve that error - if it was coming from the template.

In the component class, you also need to initiate the this.pdfViewerAutoLoad property before you can assign a value to it's pdfSrc property.

Tip: you can skip this. when accessing class properties in the template.

ulmas
  • 2,203
  • 16
  • 22
0

Look, you are trying to hide something with it's own definition. Your ViewChild ref will get the component instance once the element become visible, but that will never happen because it depends on the component itself. Maybe you should catch your PDF source inside another variable and link your ngIf with it.

Dave
  • 11
  • 2