Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NgModel on Input type file

I'm trying to make a binding to an input field type file through ngModel on the typical Angular way like this:

<input type="file" id="fileUpload" [(ngModel)]="file">

and

files:any

My problem is that after I have chosen a file, the value of my variable files is still undefined Here an example with stackblitz: https://stackblitz.com/edit/angular-6mbdww

like image 325
Leonzen Avatar asked Jan 18 '18 11:01

Leonzen


People also ask

What is [( ngModel )] used for?

The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

What can I import using ngModel?

To use NgModel we need to import FormsModule and add it to imports attribute of @NgModule in our module file.

Do I need to import ngModel?

If the user changes the value inside the input field, the Angular property will also change its value. The ngmodel directive is not part of the Angular Core library. It is part of the FormsModule library. You need to import the FormsModule package into your Angular module.


1 Answers

You have to do it externally through (change) event

<input (change)="onFileChange($event)" type="file" id="fileUpload">

And access in the ts file like the below code

  files: any[];

  onFileChange(event){
    this.files = event.target.files;
    console.log(event);
  }
like image 130
Ashraful Islam Avatar answered Oct 29 '22 23:10

Ashraful Islam