Show Image Preview Before Uploading in Angular 14

Angular show image preview before uploading tutorial, In this extensive guide, you will determine how to show image preview before uploading in an angular application using the profound FileReader object.

The FileReader object gives freedom to asynchronously read the contents of files saved on the user’s device, utilising File or Blob objects to stipulate the file or data to read.

The File object is gathered through a FileList object that returns the user’s file data through an HTML form input element.

Not just that, you will also find out how to add the Mime type validation for file type validation with the help of accept=”” tag in response to form file input element.

The accept attribute is also known as a unique file type specifier, the value is declared in string form. Every file tye specifier accepts individually or simultaneously .jpg, .pdf, doc, audio/*, video/* or image/* specifiers.

Angular 14 Show Image Preview Example

  • Step 1: Install Angular Project
  • Step 2: Create New Component
  • Step 3: Import Reactive Forms Module
  • Step 4: Implement Image Preview in Angular
  • Step 5: Run Angular Server

Install Angular Project

Commence the first step by installing Angular CLI tool on your development machine:

npm install @angular/cli -g

Further, use the following command to manifest a new angular project on your system.

ng new ng-demo-app

Including, move to the newly generated project:

cd ng-demo-app

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, you have to manually disable the strict mode you can set “strict”: false, "noImplicitReturns": false and "strictTemplates": false inside the compilerOptions and angularCompilerOptions in tsconfig.json file.

Create New Component

Next, create a new component for handling file upload and displaying image upload preview:

ng generate component upload

Import Reactive Forms Module

Files upload is managed with form input elements, hence to communicate with form elements we need a service that listens to the form items.

Open app.module.ts file likewise import ReactiveFormsModule from ‘@angular/forms’ package also register within the imports array as suggested:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { UploadComponent } from './upload/upload.component';

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


@NgModule({
  declarations: [
    AppComponent,
    UploadComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Implement Image Preview in Angular

Next, you require to open and update the upload.component.html file:

<form [formGroup]="myForm" (ngSubmit)="submit()">

  <div *ngIf="filePath && filePath !== ''">
    <img [src]="filePath" [alt]="myForm.value.name">
  </div>

  <input type="file" accept="image/*" (change)="imagePreview($event)" />

  <input formControlName="filename" placeholder="File name">

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

Similarly, open and update the upload.component.ts:

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

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

export class UploadComponent implements OnInit {

  filePath: string;
  myForm: FormGroup;

  constructor(public fb: FormBuilder) {
    this.myForm = this.fb.group({
      img: [null],
      filename: ['']
    })
  }

  ngOnInit(): void { }

  imagePreview(e) {
    const file = (e.target as HTMLInputElement).files[0];

    this.myForm.patchValue({
      img: file
    });

    this.myForm.get('img').updateValueAndValidity()

    const reader = new FileReader();
    reader.onload = () => {
      this.filePath = reader.result as string;
    }
    reader.readAsDataURL(file)
  }

  submit() {
    console.log(this.myForm.value)
  }

}

Run Angular Server

To test the image preview in angular, you need to start the angular development server using the provided command:

ng serve

You can test the application on the suggested url:

http://localhost:4200

angular Image Preview example