Using angular 2 beta, I cannot seem to get an <input type="file">
to work.
Using diagnostic, I can see two-way binding for other type
s such as text
.
<form>
{{diagnostic}}
<div class="form-group">
<label for="fileupload">Upload</label>
<input type="file" class="form-control" [(ngModel)]="model.fileupload">
</div>
</form>
In my TypeScript file, I have the following diagnostic line:
get diagnostic() { return JSON.stringify(this.model); }
Could it be that it is the issue of not being JSON? The value is null
.
I cannot really verify the value of the input
. Уven though the text next to "Choose file ..." updates, I cannot see differences in the DOM for some reason.
I think that it's not supported. If you have a look at this
DefaultValueAccessor
directive (see https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/directives/default_value_accessor.ts#L23). You will see that the value used to update the bound element is$event.target.value
.This doesn't apply in the case of inputs with type
file
since the file object can be reached$event.srcElement.files
instead.For more details, you can have a look at this plunkr: https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info:
Try this small lib, works with Angular 5.0.0
Quickstart example with ng2-file-upload 1.3.0:
User clicks custom button, which triggers upload dialog from hidden input type="file" , uploading started automatically after selecting single file.
app.module.ts:
your.component.html:
your.component.ts:
Alternative lib, works in Angular 4.2.4, but requires some workarounds to adopt to Angular 5.0.0
There is a slightly better way to access attached files. You could use template reference variable to get an instance of the input element.
Here is an example based on the first answer:
Here is an example app to demonstrate this in action.
Template reference variables might be useful, e.g. you could access them via @ViewChild directly in the controller.
Another way using template reference variable and ViewChild, as proposed by Frelseren:
Also see https://stackoverflow.com/a/40165524/4361955
If you have a complex form with multiple files and other inputs here is a solution that plays nice with
ngModel
.It consists of a file input component that wraps a simple file input and implements the
ControlValueAccessor
interface to make it consumable byngModel
. The component exposes theFileList
object tongModel
.This solution is based on this article.
The component is used like this:
Here's the component code:
And here's the component template: