Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file Input Event type in Angular

So I have been using Angular and Typescript for a long time. I cannot seem to find out what the Type for an Input file is.

For example:

<input type="file" (change)="fileChangeEvent($event)">

fileChangeEvent(e:?????){}

All examples purely just uses event without any type, and I am curious to know if such a type even exists.

like image 741
Vaaljan Avatar asked Dec 06 '19 06:12

Vaaljan


People also ask

What type is event angular?

Angular includes $event that contains the information about an event. The type of $event depends on the target event, e.g., if the target event is a native DOM element event, then it is an object. A component should define the onShow(event) method where the type of the parameter can be KeyboardEvent, MouseEvent, etc.

How can you tell if a file is canceled and clicked on input?

The property value type=”file” tells that the type of input the user enters is a file. The property value id=”theFile” is used to link the JavaScript code to it using getElementById() method. The property value onclick=”initialize()” is used to specify the function call when the user has clicked on the input.


Video Answer


3 Answers

For Angular 10 strict-type mode, we need to mention type in parameters. You can follow this way to achieve file-list from file input event

// HTML
<input type="file" (change)="uploadFile($event)">

// TS
uploadFile(event: Event) {
    const element = event.currentTarget as HTMLInputElement;
    let fileList: FileList | null = element.files;
    if (fileList) {
      console.log("FileUpload -> files", fileList);
    }
}

Hope this helps. Please share your feedback.

like image 186
Chintan Joshi Avatar answered Oct 21 '22 07:10

Chintan Joshi


Use File

The File interface provides information about files and allows JavaScript in a web page to access their content.

Try this

component.html

<input type="file" (change)="fileChangeEvent($event.target.files)">

component.ts

fileChangeEvent(e: File[]){
    fileName = e[0];
    fileType = fileName.type;
}
like image 26
Chellappan வ Avatar answered Oct 21 '22 06:10

Chellappan வ


Angular 10 and above:

component.html

    <input type="file" (change)="upload($event)">

component.ts

  upload(event: Event) {
      const target = event.target as HTMLInputElement;
      const files = target.files as FileList;
      console.log(files);
  }
like image 20
Sajad Avatar answered Oct 21 '22 06:10

Sajad