组件.html
有一个选项可以使用文件类型的输入元素来选择文件,如下所示。所选文件应显示在具有 pdfViewer 的 div 中。默认情况下,此 div 不显示在 DOM 中。这是*ngIf='isCeFile'
在 div 上使用定义的。即默认情况下isCeFile = false
<div class='flex-align-center'>
<span style="font-weight: 500;">Client Email pdf: </span>
<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,这样页面上就不会显示空白。