Issue
I’m new in TypeScript and Angular i would like to load an image from the local disk, store this image in a variable and pass this data to another component.
Someone has some examples. I tried using an example in Javascript, but it didn’t work in TypeScrupt. In HTML file use this:
<input type="file" name="img" multiple>
I tried using the image attribute, but got an error that is undefined.
Should I pass array bytes to another component or the path to this file image?
Solution
Since TypeScript is a superset of JavaScript, You can use FileReader API directly from JavaScript even if you are using TypeScript.
On input change event, you can bind your component function to handle the event using (change)
. The event.target.files
is a FileList that allows you do directly access the files via an index ex: files[0]
and send the File Object to the FileReader.
The issue here that a single FileReader object can only read one file at a time, so in the updated example, am looping over the files recursively to ensure only one file is being processed at a time.
The result attribute contains the data as a URL representing the file’s data as a base64 encoded string.
Here is an example component using Angular 2 – TypeScript
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'images',
template: `
<input type="file" name="img" multiple (change)="onChange($event)">
<div *ngFor="let fileUrl of base64Files">
<img [src]="fileUrl" />
</div>
`
})
export class ImagesComponent implements OnInit {
public base64Files: string[] = [];
private files: any[] = [];
private fileReader = new FileReader();
public onChange(event: Event) {
let files = event.target['files'];
if (event.target['files']) {
console.log(event.target['files']);
this.readFiles(event.target['files'], 0);
}
};
private readFiles(files: any[], index: number) {
let file = files[index];
this.fileReader.onload = () => {
this.base64Files.push(this.fileReader.result);
if (files[index + 1]) {
this.readFiles(files, index + 1);
} else {
console.log('loaded all files');
}
};
this.fileReader.readAsDataURL(file);
}
}