{

Angular upload file with primeng | p-fileUpload example


Primeng Angular 13  file upload example

primeng is a Rich UI component library for angular framework, It provides a lot of reusable components like buttons, input controls, data tables, and File upload.

This blog explains the integration of Primeng in the latest Angular versions and upload button with examples. It also explains how to hide/showprimeng` upload buttons.

Create a new application

First, Let’s create a new application angular-upload using the angular cli tool, ie ng command.

Next check ng command is installed or not.

ng --version

if the version is not displayed and gives `ng command not found error, Install Angular cli tool using the below command.

npm install -g @angular/cli

Create an Angular application using ng new command

ng new angular-upload

This creates a new application angular-upload application folder.

Go to the application folder in a terminal window.

Adding primeng to Angular application

You have to install primeng and icons dependencies in Angular application using npm install command

npm install primeng --save
npm install primeicons --save

This installs dependencies into an angular application and adds the below entries in package.json

  "dependencies": {
    "primeicons": "^4.1.0",
    "primeng": "^11.2.3"
  }

Primeng dependencies are added to the project, Next, we need to add styles.

Adding primeng styles and icons to Angular project

primeng components need three kinds of CSS styles required to add in angular project

  • theme file, Theme file is needed as every component in primeng changes its styles as per the theme. You can check different themes available in the node_modules/primeng/resources/themes/ folder of your project
  • core CSS styles are the primary styles required. primeng.min.css
  • icon file, Each component inbuilt integration with primeicons, you can check more here.

Angular.json is added with the below entries.

"styles": [
              "src/styles.css",
              "node_modules/primeng/resources/themes/nova/theme.css",
              "node_modules/primeng/resources/primeng.min.css",
              "node_modules/primeicons/primeicons.css"
            
],

Primeng provides each component in the form of Angular modules,

So, to add the upload button, the FileUploadModule module needs to be imported into the Angular module.

Import FileUploadModule in App.module.ts

import file upload module into app.module file so that upload components are available in primeng application.

Let’s create a basic file upload component

Basic File upload example

First Create an angular component using the ng g c componentname command.

B:\\angular-upload>ng g c BasicFileUpload
CREATE src/app/basic-file-upload/basic-file-upload.component.html (32 bytes)
CREATE src/app/basic-file-upload/basic-file-upload.component.spec.ts (691 bytes)
CREATE src/app/basic-file-upload/basic-file-upload.component.ts (317 bytes)
CREATE src/app/basic-file-upload/basic-file-upload.component.css (0 bytes)
UPDATE src/app/app.module.ts (671 bytes)

A simple component is created,

Let’s add p-fileUpload component into html template

In HTML template

<p>
  Basic Primeng Upload
</p>
<p-toast position="top-left"></p-toast>

<p-fileUpload name="docs[]" multiple="true" accept="image/*" maxFileSize="2000000" [showUploadButton]="true">
</p-fileUpload>

Typescript component code

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-basic-file-upload',
  templateUrl: './basic-file-upload.component.html',
  styleUrls: ['./basic-file-upload.component.css']
})
export class BasicFileUploadComponent implements OnInit {


  ngOnInit(): void {
  }

  onSelectEvent(event) {
    console.log("Selected files", event);
  }
}
}

File upload button on webpage is Primeng Angular File upload examples

How to Hide upload button in upload?

Sometimes we want to customize the file upload button to hide some of the buttons.

By default, p-fileUpload component provides choose, upload, cancel buttons.

show or hide buttons can be done with attributes or CSS styles

attribute It has the following attributes to enable or disable upload buttons.

showUploadButton - Boolean value to enable or disable upload button showCancelButton - Boolean value to enable or disable cancel button

the below code disables the upload and cancels button

<p-fileUpload name="docs[]" multiple="true" accept="image/*" maxFileSize="2000000" [showUploadButton]="true"
  [showCancelButton]="true"> </p-fileUpload>

The above code only disables buttons, stills buttons are visible but not clickable on a page With CSS, you can have full control.

Css code to disable cancel button

.p-fileupload .p-fileupload-buttonbar button:nth-child(3):disabled{
  opacity: 0.5;
  cursor:default;
}

CSS code to hide upload button

.p-fileupload .p-fileupload-buttonbar button:nth-child(2){
display:none;

p-fileUpload options

p-fileUpload component has following inbuilt to customize upload components.

maxFileSize - Provide value in bytes to restrict uploaded documents size. accept - It enable to restrict uploaded file types like xlsx,application/msexcel for excel files. multiple - Allows configuring single or multiple file upload. If this attribute is not there, only supports a single file.

customUpload - Boolean value indicates whether the upload process is manual or custom.

p-fileUpload events

The following events are provided to customize the upload behavior. the following handers retrieve the files using property event.files.

onBeforeUpload - This event will be called before the upload process starts. It will be useful to rename the uploaded filenames. onUpload - This will be fired once the upload process is completed onError - Called during an error in uploading a file onProgress - This event is configured to get the status of an upload file process. This will be very useful to add status or progress bar on uploading large files. uploadHandler - This will be configured and fired when the custom=“true” attribute is set. We have to provide custom upload manual logic.

upload errors

This section explains errors that occurred in the integration of primeng file uploading in the Angular application. NullInjectorError: No provider for MessageService!

If you want to display upload process errors or information messages, We can use toast or custom alerts.

You have to use toast in Angular component like this, you have to pass in the constructor MessageService is required to pass toast information during the upload process

  constructor(private messageService: MessageService) { }

You used to get the following errors.

ERROR NullInjectorError: R3InjectorError(AppModule)[MessageService -> MessageService -> MessageService]: 
  NullInjectorError: No provider for MessageService!
    at NullInjector.get (http://localhost:4200/vendor.js:26101:27)
    at R3Injector.get (http://localhost:4200/vendor.js:26268:33)

Solution, First, import MessagesModule int app.module.ts

import { MessagesModule } from 'primeng/messages';

@NgModule({
  declarations: [
    AppComponent,
    BasicFileUploadComponent
  ],
  imports: [
    MessagesModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Second, Declare providers:[MessageService] in the Angular component

import { MessageService } from 'primeng/api';

@Component({
  selector: 'app-basic-file-upload',
  templateUrl: './basic-file-upload.component.html',
  styleUrls: ['./basic-file-upload.component.css'],
  providers: [MessageService]
})
export class BasicFileUploadComponent implements OnInit 

You can check stackblitz primeng upload full source code here

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.