lew*_*tur 15 typescript angular
我正在编写一个带有文件选择器的组件,该文件选择器将文件上传到我们的CDN.我正在尝试在此组件上添加一个反应形式以验证图像输入,因此我可以检查文件名/扩展名等,并将其包装在一个表单中,这样我就可以保持Angulars验证的好处.
我的组件HTML是
<form class="mt-4" [formGroup]="form">
<div class="form-group form-inline">
<label class="btn btn-secondary btn-file">Browse
<input name="file" type="file" (change)="onChange($event)" formControlName="imageInput"
</label>
<p *ngIf="file" class="pl-4 align-middle mb-0">{{file.name}}</p>
</div>
<button type="button" class="btn btn-primary">Upload</button>
</form>
Run Code Online (Sandbox Code Playgroud)
我的组件代码是
onChange(event: EventTarget) {
// file picker code
this.form = this.formBuilder.group({
imageInput: [this.file.name, CustomValidators.imageValidator]
});
}
Run Code Online (Sandbox Code Playgroud)
在CustomValidars.imageValidator刚刚记录在一分钟输入.
加载组件时,错误消息显示为 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.
基本上,我想在我的反应形式中使用文件输入,所以我可以验证文件名.
Tou*_*afi 32
正如@ibrahim提到它尚未实现,但我遇到了同样的问题,并使用hidden字段解决了它.在onFileChange方法设置file.name为hidden字段,您可以在其中进行验证.
<form class="mt-4" [formGroup]="form">
<div class="form-group form-inline">
<label class="btn btn-secondary btn-file">Browse
<input name="file" type="file" (change)="onFileChange($event)">
<input type="hidden" name="fileHidden" formControlName="imageInput"/> <!-- Validation Field -->
</label>
<p *ngIf="file" class="pl-4 align-middle mb-0">{{file.name}}</p>
</div>
<button type="button" class="btn btn-primary">Upload</button>
</form>
onFileChange($event) {
let file = $event.target.files[0]; // <--- File Object for future use.
this.form.controls['imageInput'].setValue(file ? file.name : ''); // <-- Set Value for Validation
}
fileName = '';
this.form = this.formBuilder.group({
imageInput: [fileName, Validators.required]
});
Run Code Online (Sandbox Code Playgroud)