Angular – Preview Image before Saving it

I came across a few samples of how to preview an image before saving it. So he’s my version “Angularfied”!

Here’s the app.component.ts (obviously move as you wish!)

import { Component } from '@angular/core';
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  // This is our callback to get the URL out of the onload function
  private  urlPointer: (name: string) => void;
  // Our temp url value
  url: string;
    loadFileTest triggered by (change)='loadFileTest($event)' in the html
  loadFileTest(event) {
    this.getFileForPreview(, this.urlPointer = (url) => this.setLocalURL(url));
    fileInput - from the change event
    callbackFunction - pointer to our callback function (setLocalURL)
  getFileForPreview(fileInput, callbackFunction) {
    const reader = new FileReader();
    reader.onload = function(){
      // setLocalURL with reader.result (a string)
    // This is what actually creates our URL
  setLocalURL(url: string) {
    // Our call back function which gets the url and saves it to our url variable
    this.url = url;

Then we just need to add the following HTML

<input type='file' accept='image/*' (change)='loadFileTest($event)'><br>
<img id='output' src='{{ url }}'>

As easy as that! 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s