Angular 8|9 Show Image Preview with Reactive Forms Tutorial

By Digamber Rawat Last updated on
Today in this Angular 8|9 tutorial, we are going to understand how to show image preview before uploading to the server in Angular app. We will take the help of the HTML input element to upload the selected image. I have come across a straightforward method through which we can show the image preview to the user before uploading image to the server.

We will also learn to apply validation for uploading only images using HTML5 new FileReader() api.

Set up Angular 8|9 App

Enter command and hit enter to set up Angular 8 project:

ng new angular-image-preview

# ? Would you like to add Angular routing? No
# ? Which stylesheet format would you like to use? CSS
cd angular-image-preview

Run command to create component to manage the file preview in Angular 8.

ng g c fileUpload

# CREATE src/app/file-upload/file-upload.component.css (0 bytes)
# CREATE src/app/file-upload/file-upload.component.html (26 bytes)
# CREATE src/app/file-upload/file-upload.component.spec.ts (657 bytes)
# CREATE src/app/file-upload/file-upload.component.ts (288 bytes)

Import ReactiveFormsModule in App Module

Import ReactiveFormsModule service in app.module.ts file.

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    ReactiveFormsModule
  ],
})

export class AppModule { }

Set up Image Preview Component

In the next step, go to file.upload.component.html file and include the following code.

<form [formGroup]="uploadForm" (ngSubmit)="submit()">
  <!-- Select File -->
  <input type="file" accept="image/*" (change)="showPreview($event)" />

  <!-- Image Preview -->
  <div class="imagePreview" *ngIf="imageURL && imageURL !== ''">
    <img [src]="imageURL" [alt]="uploadForm.value.name">
  </div>

  <!-- Assign Image Alt -->
  <input formControlName="name" placeholder="Enter name">

  <button type="submit">Submit</button>
</form>

The HTML’s <input type="file"> element is used to deal with files. To accept only image files we are using HTML5’s accept attribute and passed "Image/*" attribute in it. The accept attribute allows user to pick the file through input dialog box, you can allow various file types with accept attribute.

Below are the file extension can be set using accept attribute, to know more about accept attribute click here.

<input accept="file_type | audio/* | video/* | image/* | media_type">

We declared the (change)="..." event, so whenever any change occurs in the value, the image data will be updated as per the file picked by the user.

To show the image preview in Angular 8, we declared the img HTML tag and bind the src tag to the variable. We will assign the image URL to the src variable using the new FileReader() method.

Image Preview Before Uploading in Angular 8/9

Go to file-upload.component.ts file and add the given below code inside of it.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from "@angular/forms";

@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.css']
})

export class FileUploadComponent implements OnInit {
  imageURL: string;
  uploadForm: FormGroup;

  constructor(public fb: FormBuilder) {
    // Reactive Form
    this.uploadForm = this.fb.group({
      avatar: [null],
      name: ['']
    })
  }

  ngOnInit(): void { }


  // Image Preview
  showPreview(event) {
    const file = (event.target as HTMLInputElement).files[0];
    this.uploadForm.patchValue({
      avatar: file
    });
    this.uploadForm.get('avatar').updateValueAndValidity()

    // File Preview
    const reader = new FileReader();
    reader.onload = () => {
      this.imageURL = reader.result as string;
    }
    reader.readAsDataURL(file)
  }

  // Submit Form
  submit() {
    console.log(this.uploadForm.value)
  }

}
  • We are using Reactive Forms approach within in Angular 8 to handle image upload. Now we initialized it by assigning FormGroup service to uploadForm at the beginning.
  • The imageURL variable is used to pass the base64 URL to the img element.
  • Inside the showPreview function, we passed the JavaScript default event object as an argument to extract the image file. Now, here, we need to explicitly define the HTMLInputElement type because Angular doesn’t know that the file type we are targeting exists or not. It might through an error. (event.target as HTMLInputElement)
  • As you can see, we stored the name and avatar value in the form control already. For the avatar property, we won’t bind the avatar value to the formControlName with the HTML element as we already did for the name property. Therefore we will be using Angular 8’s patchValue({ }) service to bind the image value
  • The updateValueAndValidity() method informs Angular whenever the user makes any change. Technically this method tells Angular and Recalculates the value and validation status of the control.
  • Then we will convert image to dataURI by using the FileReader API. Finally, we will set the dataURI to imageURL variable, then pick the image from your device, and you will see the image preview in Angular 8 application.

Conclusion

Finally, we are done with Angular 8/9 Image Preview tutorial. I hope you loved this tutorial, please share it with others.

Check out the Git repo if you find any difficulty while working on this topic.

Git Repo

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Thanks for checking this tutorial out :) Let me know if you have any suggestions or issue related to this tutorial, or you want to request a new tutorial. Just shoot me a mail here.