1

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.

Community
  • 1
  • 1
Sailoosha
  • 193
  • 1
  • 3
  • 14

3 Answers3

12

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.

mutex
  • 7,536
  • 8
  • 45
  • 66
3

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>
Ammar Hasan
  • 2,436
  • 16
  • 22
  • Thanks so much for the suggestion. target.files seems to work. However , I am unable to implement like this document.getElementById('fileInput').files) . It seems to be working fine when debugging and I am getting the values but since I'm using TypeScript, its throwing me error when writing the code. Filereader is in lib.d.ts – Sailoosha Mar 05 '16 at 16:32
  • I am still having another issue when trying to implement your solution. http://stackoverflow.com/questions/35816670/function-is-not-defined-referecenerror-onchange-in-angularjs – Sailoosha Mar 05 '16 at 16:36
  • I'll try to look into that issue, but never have worked on Kendo :( – Ammar Hasan Mar 05 '16 at 17:06
2

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;
}
Steve
  • 11,696
  • 7
  • 43
  • 81