Angular Directives for Handle Image upload

Umesh Thapa
JavaScript in Plain English
3 min readMar 25, 2023

--

For handling image/file upload handling in Angular we can use below code. We can also change the file size and file type also.

Firstly Create a directive NgImageUploadDirective

import { Directive, EventEmitter, HostListener, Input, Output } from '@angular/core';

@Directive({
selector: '[ngImageUpload]'
})
export class NgImageUploadDirective {

@Input() maxSize: number = 5242880; // 5MB in bytes
@Output() imageUploaded = new EventEmitter<File>();

constructor() { }

@HostListener('change', ['$event.target.files']) handleImageUpload(files: FileList) {
const file = files.item(0);
if (!file) return;

// Check file type
const allowedTypes = ['image/png', 'image/jpeg', 'image/gif'];
if (!allowedTypes.includes(file.type)) {
alert('Invalid file type. Only PNG, JPEG and GIF images are allowed.');
return;
}

// Check file size
if (file.size > this.maxSize) {
alert('File size exceeds limit. Maximum allowed size is 5MB.');
return;
}

// Emit event with file object
this.imageUploaded.emit(file);
}

}

This directive listens for the change event on an input element with the ngImageUpload selector, which triggers when a user selects an image to upload. The handleImageUpload() function then performs some validation checks on the selected file, such as checking its file type and size. If the file passes these checks, it emits an event with the selected file object, which can then be used by the parent component.

To use this directive in your component’s HTML template, you would simply add the ngImageUpload attribute to an <input> element that allows file uploads:

<input type="file" ngImageUpload (imageUploaded)="handleImageUpload($event)">

In this example, the imageUploaded event is bound to the handleImageUpload() function in the component, which receives the uploaded file object as its argument. You can then perform additional actions with the uploaded file as needed.

  1. @Directive({ selector: '[ngImageUpload]' }): This decorator defines the directive and specifies its selector, which in this case is [ngImageUpload]. This means that the directive will be applied to any element that has the ngImageUpload attribute.
  2. @Input() maxSize: number = 5242880;: This decorator defines an input property called maxSize, which specifies the maximum allowed file size for image uploads. By default, the maximum size is set to 5MB in bytes.
  3. @Output() imageUploaded = new EventEmitter<File>();: This decorator defines an output property called imageUploaded, which is an event emitter that will be used to emit the uploaded image file to the parent component.
  4. @HostListener('change', ['$event.target.files']): This decorator listens for the change event on the host element (i.e. the element to which the directive is applied) and passes the target.files property of the event as an argument to the handleImageUpload() function.
  5. handleImageUpload(files: FileList) { ... }: This function takes a FileList object as its argument, which represents the list of files that were selected for upload. In this case, we only handle the first file in the list, so we use the item() method to get the first file object.
  6. const allowedTypes = ['image/png', 'image/jpeg', 'image/gif'];: This array specifies the allowed file types for image uploads. In this case, we only allow PNG, JPEG, and GIF images.
  7. if (!allowedTypes.includes(file.type)) { ... }: This condition checks if the selected file's type property is one of the allowed types. If the file is not an image or is not one of the allowed types, an error message is displayed to the user.
  8. if (file.size > this.maxSize) { ... }: This condition checks if the selected file's size property exceeds the maximum allowed size.

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

Interested in scaling your software startup? Check out Circuit.

--

--

Web Design || Development || Content Creator || Editor || Writer || Ewumesh || Nepal || Australia || USA #ewumesh https://ewumesh.com/