angular - 手动设置 FormBuilder 控件值时出现 DOMException

标签 angular

我正在尝试手动将 FileReader 中的数据设置为控制值(“图像”)。当我将“reader.result”(存储二进制图像数据)设置为“image”FormControl 时,出现错误:

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.

我的组件:

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 模板:

    <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>

我想将二进制图像数据保存在 FormControl 图像中。

最佳答案

使用 formBuilder 时不要使用 new FormControl() ( docs ),它应该是这样的:

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

删除您的 formControlName="image" (顺便说一下,它应该是 [form]="formProducts" 父级的子级) 因为您已经在 uploadImage() 方法中将输入值“链接”到您的 FormGroup,并且因为如错误消息中所述,这会尝试设置 value属性而不是文件名

您可以查看this answer如果您想执行自己的 FileInputValueAccessor 指令。

关于angular - 手动设置 FormBuilder 控件值时出现 DOMException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54246313/

相关文章:

html - 根据屏幕尺寸更改面板尺寸

javascript - 如何使用来自 http 请求的数组将动态输入字段添加到 Angular 形式

html - Angular - 使用 *ngfor 时未定义的属性,(更改)

java - Angular元素在制作后显示白页

angular - 使用不同的环境设置运行 ng build --prod

node.js - Angular <app-root> 在 Node View 中无法识别

Angular2 - 在不同环境中执行端到端测试

angular - 如何在不使用表单的情况下将输入字段设置为无效,以便底部轮廓根据条件显示为红色

500 个服务器错误的 Angular 句柄

angular - TemplateRef createEmbeddedView(context : C) vs ViewContainerRef createEmbeddedView) 之间的区别