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?
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.
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']
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With