0

组件.html

有一个选项可以使用文件类型的输入元素来选择文件,如下所示。所选文件应显示在具有 pdfViewer 的 div 中。默认情况下,此 div 不显示在 DOM 中。这是*ngIf='isCeFile'在 div 上使用定义的。即默认情况下isCeFile = false

        <div class='flex-align-center'>
          <span style="font-weight: 500;">Client Email pdf: </span>
          &nbsp;
                
          <mat-icon color='primary' (click)="ceFilePicker.click()" style="cursor: pointer;">
            add_circle
          </mat-icon>
        </div>

        <input type="file" accept=".doc, .docx, .pdf"
         (change)="onChange($event, 'CLIENT-EMAIL')" (click)="$event.target.value=null"
         #ceFilePicker style="margin: 0; visibility: hidden;">

      // PDF Viewer Div
      <div class='flex' *ngIf='isCeFile'>
        <div style="width: 49%; height: 60vh; margin-right: 1%;">
          <ng2-pdfjs-viewer #pdfViewerAutoLoadCE
          [download]="false" [print]="false" [openFile]="false"
          [fullScreen]='false'></ng2-pdfjs-viewer>
        </div>
  
      </div>

组件.ts

处理文件输入的方法会更改 ngIf 中用于 pdfViewer div 的变量。但是,在执行此方法时,div 未初始化。因此,未定义 pdfViewer 元素。因此所选文件不会分配给 pdfViewer。

onChange()有没有办法在语句之前的方法内初始化div,即初始化pdfViewer元素this.pdfViewerAutoLoadCE.pdfSrc = this.clientEmailFile;

  isCeFile = false;
  @ViewChild('pdfViewerAutoLoadCE') pdfViewerAutoLoadCE;

  onChange(event, docType) {
    
      this.clientEmailFile = event.target.files[0];
      this.ceFileChanged = true;
      this.isCeFile = true;
      console.log('this.pdfViewerAutoLoadCE', this.pdfViewerAutoLoadCE);
      // console output: undefined
      
      this.pdfViewerAutoLoadCE.pdfSrc = this.clientEmailFile;
      this.pdfViewerAutoLoadCE.refresh();

  }

截至目前,我在 pdfViewer div 上使用没有 ngIf 的它,它工作正常。但是,只需要在需要的时候才显示这个div,这样页面上就不会显示空白。

4

1 回答 1

0

一种方法是ng-template改用。如果不满足此条件,请显示其他内容。因此,当布尔值打开时,div 会发生变化。由于我不确定div您要渲染哪个,哪个不渲染,您可能需要更改 的深度*ngIf="isCeFile; else noFile",但我希望您能理解。https://angular.io/api/common/NgIf#showing-an-alternative-template-using-else


<div class='flex'>
<div style="width: 49%; height: 60vh; margin-right: 1%;">
<ng-container *ngIf="isCeFile; else noFile">
          <ng2-pdfjs-viewer #pdfViewerAutoLoadCE
          [download]="false" [print]="false" [openFile]="false"
          [fullScreen]='false'></ng2-pdfjs-viewer>
</ng-container>

</div>
</div>

<ng-template #noFile>
   <div> 
   Oops, no file.
   </div>
</ng-template>
于 2022-01-31T12:53:15.987 回答