Search code examples
javascriptangularprimengprimeng-menu

How can I prompt user to upload file from within a PrimeNG menuItem in angular


I have a menu item like this

 items = [{
            label: 'Upload', icon: 'pi pi-plus', command: (event) => { //get the event.target.file and pass it into a service that will manage the rest},
...
        }]

So in the Html I am using the <p-menu> like this

<p-menu [model]="items"></p-menu>

And all the labels and icons are being displayed correctly. But how do I get the upload to open a prompt for file upload like a <input type='file'> so that I can get the event.target.file to pass to the service being called in the command?


Solution

  • As far as my research goes there is no feature in PrimeNg that makes this easier. Inorder to prompt the user for a file upload I had to create an input file type and then get the files after calling the click() event on it

    So in the menuItem I call the prompt which then calls the service.

    items = [{label: 'Upload', icon: 'pi pi-plus', command: () => {upload_prompt( )}]

    upload_prompt( ): void {
    
            const input = document.createElement( 'input' );
            input.type = 'file';
            input.multiple = true;
    
            input.onchange = () => {
                let file = input.files as FileList;
                file_upload_service( file )
            }
            input.click()
        }
    

    Hope this helps someone.