我正在尝试手动将 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/