Angular 2 allows the user to select and image from their local machine

I am very new to Angular. I am trying to create a simple web application using Angular 2, where I allow users to select and image from their local computer. Then I want to display this image in the tag <img>. Later, perform actions on the image, for example, rotate, change the scale, change the 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 this does not work at all. How to view image and update src attribute using Angular2?

I'm just trying to find out Angular. :)

Is there a better and easier way to do this?

+4
source share
4 answers

, onloaded. , 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]);
    }
}

ElementRef .

+6

, angular: EventTarget

:

this.url = event.target['result']
+2

, Angular 2/Typescript, ' 'EventTarget'   e :

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

:

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

Source: https://habr.com/ru/post/1628428/


All Articles