Angular 5 how to get file name from input with type = file

Miger picture Miger · Jul 26, 2018 · Viewed 22k times · Source

I know there are simmilar questions but none cover the method for Angular 5 or at least not in a way that I understand it.

For my image upload system I need to know if a picture is attached to the input tag and what name the file has. Here is my code:

HTML:

<input 
  type="file" 
  [(ngModel)]="currentInput"
  (change)="onFileSelected($event)"
>

Angular:

export class ImageUpload {
    currentInput;

    onFileSelected(event) {
        console.log(this.currentInput);
    }
}

No matter if there is a file attached or not the value in "currentInput" is always undefined. How does this work with input when the type is equal to "file"?

Thanks!

Answer

Ramesh Rajendran picture Ramesh Rajendran · Jul 26, 2018

Try this below way

onFileSelected(event) {
 if(event.target.files.length > 0) 
  {
    console.log(event.target.files[0].name);
  }
}