Angular 和 PrimeNg FileUploader:如何在渲染组件时显示所选文件的列表?

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

我正在使用 Angular 17 和 PrimeNg 17 转载人在这里:

链接

我的目的是让一个或多个预选文件显示在所选文件列表中。正如你所看到的,我在

this.fileUpload._files.push(file)
内部调用
ngAfterViewInit
,预期的结果是让该文件出现在文件列表中。相反,它仅在单击“选择”时显示。我还添加了一个变更检测器,但它仍然不起作用。

我怎样才能实现这个目标?

angular file-upload primeng
1个回答
0
投票

我在

detectChanges
组件中调用了
ChangeDetectorRef
FileUpload
,然后文件就开始出现了!

 ngAfterViewInit(): void {
    if (this.fileUpload) {
      this.fileUpload._files.push(this.file);
      this.fileUpload.cd.detectChanges(); //   <-changed here!
      this.cdr.detectChanges();
    }
  }

完整代码

import {
  AfterViewInit,
  ChangeDetectorRef,
  Component,
  ViewChild,
  inject,
} from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { FileUpload, FileUploadModule } from 'primeng/fileupload';

@Component({
  selector: 'app-root',
  standalone: true,
  templateUrl: './app.html',
  imports: [FileUploadModule],
})
export class App implements AfterViewInit {
  cdr = inject(ChangeDetectorRef);
  file = new File([''], 'filename');

  @ViewChild('fileUpload') fileUpload!: FileUpload;

  ngAfterViewInit(): void {
    if (this.fileUpload) {
      this.fileUpload._files.push(this.file);
      this.fileUpload.cd.detectChanges();
      this.cdr.detectChanges();
    }
  }
}

bootstrapApplication(App);

Stackblitz 演示

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