How to trigger PrimeNG <p-fileUpload> file dialog by clicking a custom icon?

Discussão em 'Angular' iniciado por Clinton Hadrian, Abril 23, 2025.

  1. I’m using Angular 18 and PrimeNG 17.x, and I want to open the file upload dialog of a component when I click a custom icon, like a file-excel icon.

    What I Tried I tried two methods:

    Calling .choose() on the p-fileUpload reference.

    Trying to trigger a hidden inside the p-fileUpload using ElementRef.

    Neither of these opened the file dialog.

    My Code HTML

    <!-- Icon to click -->
    <i
    (click)="triggerUpload()"
    *ngIf="tab.content === 'paymentXlsx'"
    class="pi pi-file-excel"
    style="cursor: pointer;"
    ></i>

    <!-- PrimeNG File Upload -->
    <p-fileUpload
    #paymentXLSXComp
    mode="basic"
    accept=".xlsx, .xlx"
    maxFileSize="1000000"
    [customUpload]="true"
    (uploadHandler)="onUploadPaymentXlx($event)"
    [fileLimit]="1"
    >
    <!-- I tried exposing the internal file input -->
    <ng-template pTemplate="content">
    <input
    #fileInput
    type="file"
    (change)="paymentXLSXComp.onFileSelect($event)"
    style="display: none"
    />
    </ng-template>
    </p-fileUpload>


    Component TS

    @ViewChild('fileInput', { static: false }) fileInput!: ElementRef<HTMLInputElement>;

    triggerUpload() {
    console.warn('Attempting to trigger upload...');
    if (this.fileInput) {
    this.fileInput.nativeElement.click(); // not working
    } else {
    console.warn('fileInput is undefined');
    }
    }


    ❌ Problem Clicking the icon logs the message but does not open the file picker dialog.

    I removed the hidden attribute to ensure the DOM is rendered.

    I also tried calling .choose() on the p-fileUpload component ref — it also doesn’t work.

    ✅ What I'm Looking For How can I reliably trigger the file input of p-fileUpload by clicking a custom icon or button outside the component?

    Continue reading...

Compartilhe esta Página