I am using Angular 17 with PrimeNg 17 Reproducer here:
My intention is to have one or more preselected files that are displayed in the selected files list. As you can see, I am calling this.fileUpload._files.push(file)
inside ngAfterViewInit
, and the expected result is to have the file in the file list. Instead, it shows up only when clicking 'Choose'. I also added a change detector but it still does not work.
How can I achieve this?
I called the detectChanges
of the ChangeDetectorRef
inside the FileUpload
component, then the file started appearing!
ngAfterViewInit(): void {
if (this.fileUpload) {
this.fileUpload._files.push(this.file);
this.fileUpload.cd.detectChanges(); // <-changed here!
this.cdr.detectChanges();
}
}
full code
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);