Search code examples
angularngmodel

(change) vs [(ngModel)] with input type file in Angular


I am new to Angular and got confused between (change) event and (ngModel). Are both of them used for tracking state of the form? Can I use ngModel as (change) or which one is better? The problem is that when I have a form with input type="file".

When I use (ngModel) <input type="file" [(ngModel)]="link" name="link"/> and get the value by this.link. In the backend, it returns a null object {}.

But when I use (change) <input type="file" name="link" (change)="fileUploadChange($event)"/> and get the file with function

fileUploadChange(event){ this.link = event.target.files[0]; }

In the backend, it returns the file path as I want. {link: {path: "C://..." }}

So can I use (ngModel) for input type="file" in any way?


Solution

    • [(ngModel)] vs (change):

    • [(ngModel)]:

      we need to import formsModule in the module in which we want use ngModel. ngModel is used for to way binding. it's continues track your each input. ngModel is not formControlName and not formControl as per angular.

    • (change):

      On change event is called only when value is changed from it's previous state. in on change event we need to pass the event and need to fetch value from event like. event.target.value.

      [(ngModel)] and (change) event with input type = "file" .

      if we are using ngModel with file input we only get the fakepath, like. C:\fakepath\Screenshot from 2019-12-13 15-03-17.png

      and if we are using it with change event:

      html

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

      ts

      uploadFile(event){ this.file1 = event.target.value; this.file2 = event.target.files[0]; console.log(this.file1) // in this case we only get fakepath same as we get in ngModel. console.table(this.file2) // in this case we get object with data like, name, lastModified, lastModifiedDate, size and type. }

      and i personally think change event is better to use with input type file.