Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  186] [ 5]  / answers: 1 / hits: 67297  / 6 Years ago, wed, may 23, 2018, 12:00:00

I have this code to show the image preview before uploading it. However I am working with Angular 5 so I have a .ts file instead of a .js one. How can I do the same in Angular 5? I also want to show the image in all browsers.


My HTML:


<input type='file' onchange="readURL(this);"/>
<img id="blah" src="http://placehold.it/180" alt="your image"/>

My CSS:


img {
max-width:180px;
}

input[type=file] {
padding: 10px;
background: #2d2d2d;
}

My JavaScript:


function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById('blah').src=e.target.result
};
reader.readAsDataURL(input.files[0]);
}
}

More From » angular

 Answers
11

.html



Update event attr and handler param for input.
And you should use data binding for src attribute. Following will apply src if it's not null or undefined or hardcoded url ('http://placehold.it/180')



<input type='file' (change)=readURL($event); />
<img id=blah [src]=imageSrc || 'http://placehold.it/180' alt=your image />


.ts



In component ts file (class) you should have property imageSrc which be used in view (html) and your function should be a method of that class



...
imageSrc: string;
...
constructor(...) {...}
...
readURL(event: Event): void {
if (event.target.files && event.target.files[0]) {
const file = event.target.files[0];

const reader = new FileReader();
reader.onload = e => this.imageSrc = reader.result;

reader.readAsDataURL(file);
}
}

[#54368] Saturday, May 19, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
karladaijahf

Total Points: 78
Total Questions: 123
Total Answers: 89

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
;