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.
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;
}
}
}
}
我认为id是“ image”,没有“#”,因为您使用的是getElementById方法。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.