I am very new to angularjs. I wasn't able to find the solution online.
I would like to read the text from a file. I was trying to follow this example.
FileReader not loading file properly using AngularJS
However, since I'm using TypeScript, I receive this error for this line
document.getElementById('fileInput').files[0];
Error:
Property 'files' does not exist on type 'HTMLElement'.
Please suggest me how I can cast to use the files.
This should work fine from that example, maybe you're doing something wrong there. However, you may test your code like this, replace fileChanged()
by fileChanged(event)
and then get the files by event.target.files
function fileChanged(event) {
var target = event.target || event.srcElement;
console.log(target.files);
console.log(document.getElementById('fileInput').files);
}
<div>
<input ng-model="csv"
onchange="fileChanged(event)"
type="file" id="fileInput"/>
</div>
Another way I've found around the error in the question is to replace:
document.getElementById('fileInput').files[0];
with
var input: any = document.getElementById('fileInput');
var file = input.files[0];
by defining input as type "any" the Typescript compiler no longer raises the error.
you should cast it to HTMLInputElement
. That interface has the .files
field defined to be FileList
/**
* Returns a FileList object on a file type input object.
*/
readonly files: FileList | null;
interface FileList {
readonly length: number;
item(index: number): File;
[index: number]: File;
}