5

I'm very new to Angular. I'm trying to make a simple web application using Angular 2 where I allow the users to select and image from their local computer. Then I want to display this image in an <img> tag. Later perform actions on the image like rotate, change scale, change width...etc.

This is what I have in my component

@Component({
    selector: 'image-container',
    template: `
        <input type="file" (change)="changeListner($event)" />
        <img id="image"/>
    `,
    directives: [ImageActionsComponent]
})
export class ImageContainerComponent { 
   // make FileReader work with Angular2
   changeListner(event){
        var reader = new FileReader();

        reader.onloaded = function (e) {
            // get loaded data and render thumbnail.
            var src = e.target.result;
            document.getElementById("image").src = src;
        };

        // read the image file as a data URL.
        reader.readAsDataURL(event.target.files[0]);
    }
}

But it doesn't work at all. How do I read an image and update the src attribute using Angular2?

I'm just trying to learn Angular. :)

Is there a better and easier way to do this?

Mr Lister
  • 42,557
  • 14
  • 95
  • 136
Rahal
  • 89
  • 2
  • 3
  • 6

4 Answers4

7

It doesn't work because you have onloaded event name. There is no such event, it should be onload:

import {Component, ElementRef} from 'angular2/core'

@Component({
    selector: 'image-container',
    template: `
        <input type="file" (change)="changeListner($event)" />
        <img class="image" />
    `,
    directives: [ImageActionsComponent]
})
export class ImageContainerComponent {
    constructor(private element: ElementRef) {}

    changeListner(event) {
        var reader = new FileReader();
        var image = this.element.nativeElement.querySelector('.image');

        reader.onload = function(e) {
            var src = e.target.result;
            image.src = src;
        };

        reader.readAsDataURL(event.target.files[0]);
    }
}

Also it's better to use ElementRef to locate image within a component.

dfsq
  • 182,609
  • 24
  • 222
  • 242
2

For those who faced this error with angular: property result does not exists on type EventTarget

you can work around it simply by:

this.url = event.target['result']
Taha Zgued
  • 1,007
  • 12
  • 17
1

As this answer states How to preview picture stored in the fake path in Angular 2/Typescript to avoid property 'result' does not exist on type 'eventtarget' you can also determine the type of e to be any as the following:

reader.onload = function(e: any) {
        var src = e.target.result;
        image.src = src;
    };
Mohamed Rozza
  • 547
  • 6
  • 12
0

My solution was this:

reader.onload = (e) => {
   image.src=reader.result;
}