Skip to content Skip to sidebar Skip to footer

Casting Document.getElementById To Access Files In TypeScript

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

Solution 1:

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.


Solution 2:

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>

Solution 3:

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;
}

Post a Comment for "Casting Document.getElementById To Access Files In TypeScript"