2 votes

Initial value of input type file from a FormControl

When I try to add an initial value to an input type file from a FormControl I get the following error:

ERROR DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

This is the code for my FormGroup :

this.editProduct = new FormGroup({
    'productImage' : new FormControl( '', Validators.required )
});

ngOnInit() {
    this._productsService.getProduct( this.productId )
          .subscribe( getProductData => {
    this.editProduct.controls['productImage'].setValue( 
        this.product.productImage );
    }
}

Form HTML:

<form class="animated fadeIn" [formGroup]="editProduct" 
(ngSubmit)="updateProduct()" #form="ngForm">
<input class="form-control" type="file" [ngClass]="{ 'is-invalid' : 
!editProduct.get( 'productImage' ).valid }" id="productImage" 
formControlName="productImage">
    <button class="btn btn-primary" type="submit" 
    [disabled]="!form.valid">Actualizar</button>
</form>

5voto

Pablo Lozano Points 23403

The error is quite explanatory: In the inputs of type "file" you cannot define an initial value other than "" (empty string).

It's not AngularJS thing, it's that no browser will allow you to define a default path because it would be a huge security hole: I could create a malicious page that would take a file, open it from the browser and send all the information via AJAX to my server.

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X