我正在使用 Angular 17 和 PrimeNg 17 转载人在这里:
我的目的是让一个或多个预选文件显示在所选文件列表中。正如你所看到的,我在
this.fileUpload._files.push(file)
内部调用 ngAfterViewInit
,预期的结果是让该文件出现在文件列表中。相反,它仅在单击“选择”时显示。我还添加了一个变更检测器,但它仍然不起作用。
我怎样才能实现这个目标?
我在
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);