1

I am making a simple file upload script and have only been able to find working examples that are based off of an input's (change) event. I.e. - https://www.thepolyglotdeveloper.com/2016/02/upload-files-to-node-js-using-angular-2/

<input type="file" id="userfile" class="form-control"
(change)="fileChangeEvent($event)" name='userfile'>

This works. And that's great.

However if I try to bind a file input to an ngModel it doesn't work.

template

<form class="form-signin" (ngSubmit)="onSubmit(fileForm.value)" #fileForm="ngForm">
<input type="file" id="userfile" class="form-control"
[(ngModel)]="fileUpload.userfile" name='userfile'>
<input type="text" id="random" class="form-control"
[(ngModel)]="fileUpload.random" name="random">

<button class="btn btn-lg btn-primary btn-block" type="submit">Upload File</button>
</form>

component.ts

  onSubmit(data){
    console.log("Submitted");
    console.log(data);
  }

Only the data set in the random input will show up. No files placed in the file input will show up, only as (undefined) in both my ngModel and printing out the data from onSubmit(data)

Jim Factor
  • 1,465
  • 1
  • 15
  • 24
  • Possible duplicate of [Angular 2 File upload from input type=file](http://stackoverflow.com/questions/35399617/angular-2-file-upload-from-input-type-file) – Adam Feb 15 '17 at 22:07

1 Answers1

2

I also had issues with how files were handled in Angular 2, so I opted for the low-tech approach that side-steps Angular 2 forms.

My template looks like this.

<input class="field" type="file" (change)="setFile($event)" />

And to access my files, I use:

private setFile(event) {
    this._files = event.srcElement.files;
}

You can then use those files.

Keep in mind uploading multi-part file data in Angular 2 also doesn't work (last time I checked), so you may have to use manual XHR request rather than the HTTP provider. See this answer for details about that.

Community
  • 1
  • 1
Adam
  • 4,445
  • 1
  • 31
  • 49