DOMException when manually set value for FormBuilder Control

Viewed 558

I am trying to manually set data from FileReader to a control value ('image'). When I set "reader.result"(stores binary image data) to "image" FormControl I'm getting an 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.

My component:

formInitBuilder() {
    this.formProducts = this.fB.group(
      {
          name: new FormControl('', Validators.required),
          description: new FormControl(''),
          detailedDescription: new FormControl(''),
          price: new FormControl('', Validators.minLength(1)),
          isNewProduct: new FormControl(true),
          promotionalProduct: new FormControl(true),
          categoryId: new FormControl('', Validators.required),
          image: new FormControl('', Validators.required)
      });
  }

  uploadImage(file: FileList) {

      this.fileToUpload = file.item(0);
      let reader = new FileReader();
      console.log(reader.result);
      reader.onload = (event: any) => {
        this.formProducts.controls['image'].setValue( reader.result);
        };
      reader.readAsDataURL(this.fileToUpload);
      }

HTML template:

    <div class="form-group">
        <div class="input-group mb-3">
          <div class="custom-file">
            <input type="file"  #Image accept="image/*"(change)="uploadImage($event.target.files)"   class="custom-file-input" id="inputGroupFile02" formControlName="image">
            <label class="custom-file-label" for="inputGroupFile02">Select image</label>
          </div>
        </div>
      </div>

I would like to save the binary image data in the FormControl image.

1 Answers

Don't use new FormControl() when using the formBuilder (docs), it should be like:

this.formProducts = this.fb.group({
  name: ['', Validators.required],
  description: [''],
});

Remove your formControlName="image" (by the way, it should be the child of a [form]="formProducts" parent) because you already "link" the input value to your FormGroup in your uploadImage() method and because, as said in your error message, this tries to set the value property instead of filename.

You can look at this answer if you want to do your own FileInputValueAccessor directive.

Related