1

I am using Angular 17 with PrimeNg 17 Reproducer here:

link

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?

1 Answer 1

1

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);

Stackblitz Demo

2
  • 1
    This worked great, thanks! I cannot upvote because I don't have enough reputation
    – codrut
    Commented Feb 20, 2024 at 9:46
  • @codrut No issues, You're welcome! :) Commented Feb 20, 2024 at 9:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.