Reputation: 172
I am trying to get the image from computer, and trying to set this image into an image element, but I get the following error.
Cannot set property 'src' of null
Can anybody help?
This is my component file code.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
event: any;
url: any;
onSelectFile = (event) => { // called each time file input changes
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(event.target.files[0]); // read file as data url
reader.onload = (event: any) => {
this.url = event.result;
console.log(this.url);
var image = document.getElementById("#image") as HTMLImageElement;
image.src = this.url;
}
}
}
}
this is my HTML file code.
<img id="image" height="200"> <br/>
<input type='file' (change)="onSelectFile($event)">
Whenever I set the value of my image element I get the error mentioned above.
Upvotes: 0
Views: 893
Reputation: 1934
Databind the src attribute of the image to the url property:
<img id="image" height="200" [src]="url">
Remove all the code after assigning the image link to the url property.
export class AppComponent {
title = 'app';
event: any;
url = '';
onSelectFile = (event) => { // called each time file input changes
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(event.target.files[0]); // read file as data url
reader.onload = (event: any) => {
this.url = event.result;
}
}
}
}
Upvotes: 2
Reputation: 92
I think the id is "image", without "#", because you are using getElementById method.
Upvotes: 0