Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 let user choose and image from their local machine

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?

like image 673
Rahal Avatar asked Feb 12 '16 05:02

Rahal


3 Answers

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.

like image 126
dfsq Avatar answered Nov 15 '22 21:11

dfsq


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']
like image 44
Taha Zgued Avatar answered Nov 15 '22 21:11

Taha Zgued


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;
    };
like image 1
Mohamed Rozza Avatar answered Nov 15 '22 19:11

Mohamed Rozza