Angular 5 file upload: Failed to set the 'value' property on 'HTMLInputElement' Angular 5 file upload: Failed to set the 'value' property on 'HTMLInputElement' angular angular

Angular 5 file upload: Failed to set the 'value' property on 'HTMLInputElement'


In my case I just removed the formControlName:

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

And .ts:

onFileChange(event) {    const reader = new FileReader();    if (event.target.files && event.target.files.length) {      const [file] = event.target.files;      reader.readAsDataURL(file);      reader.onload = () => {        this.data.parentForm.patchValue({          tso: reader.result        });        // need to run CD since file load runs outside of zone        this.cd.markForCheck();      };    }  }


Like the error is saying, you can only set an empty string to a file input value to clear the selection. It could open security risks otherwise. I can't imagine how that code could've ever worked. Maybe in some non-standard (bad) browser?

Shouldn't that code work if you just remove the line, why do you need to set the same value to the input that it already has anyway?

Edit: seems a custom ValueAccessor is needed for validating file inputs. Solution in another answer: Angular2: validation for <input type="file"/> won't trigger when changing the file to upload


Implement this by having 2 inputs for the file. Here is how I did it:

  this.myForm= this.formBuilder.group({      fileSource: ['', Validators.required],      fileName: '',    })

HTML

<input type="file" formControlName='fileSource' (change)="onFileSelected($event)"/>

Typescript

  onFileSelected(event) {    if(event.target.files.length > 0)      {       this.myForm.patchValue({          fileName: event.target.files[0],       })     }  }submit(){    const formData = new FormData();    formData.append('file', this.myForm.get('fileName').value);       this.http.post('http://localhost:3000/upload', formData)      .subscribe(res => {        console.log(res);        alert('Uploaded Successfully.');      })  }