当文件输入发生变化时,Angular 2似乎在运行验证时遇到麻烦.
我做了一个插图来说明这个问题:
我创建了一个formGroup
this.frm = new FormGroup({
file: new FormControl("", this.validateFile)
});
Run Code Online (Sandbox Code Playgroud)
在validateFile函数中,我抛出一个警报并记录到控制台:
public validateFile(formControl: FormControl): {[key: string]: any; } {
alert('Validation ran');
console.log('Validation ran');
}
Run Code Online (Sandbox Code Playgroud)
Plunkr来说明问题:https://plnkr.co/edit/Pgcg4IkejgaH5YgbY3Ar?p = preview
验证将在初始化页面时运行,但每次更改要上载的文件时都不会运行.
有没有解决这个问题的方法?
在我的前端,我使用angular6,我有这种形式,您可以通过删除文件div或单击div打开文件选择器来选择图像.
表格是
<form [formGroup]="imageUpload" (ngSubmit)="imageUploadSubmitted($event.target)" >
<div id="imageDrop" (click)='imageInput.click()' (drop)="drop($event)" (dragover)="allowDrop($event)" #imageDrop></div>
<input type="file" (change)='imageChange($event)' #imageInput id="imageInput" name = 'imageInput' accept=".png, .jpg, .jpeg, .gif" formControlName="imageInput" required >
<button type="submit" >Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
这是打字稿
selectedFile:File=null;
allowDrop(e) {
e.preventDefault();
}
drop(e) {
e.preventDefault();
this.imageUpload.controls.imageInput.reset();
this.selectedFile = e.dataTransfer.files[0];
let input = this.imageUpload.controls.imageInput as any;
input.value = e.dataTransfer.files[0];
}
imageChange(e){
this.selectedFile = e.target.files[0];
}
Run Code Online (Sandbox Code Playgroud)
因此,在删除图像时,从事件中获取它并将其放入文件输入中.提交表单后,将表单数据发送到服务进行发布.该console.log显示File对象(__proto__ : File无论你从文件选择器中选择了一个图像,或者一个下降的)div.
imageUploadSubmitted(form){
console.log('imageInput value - ', this.imageUpload.controls.imageInput.value);
this.mapcmsService.uploadImage(form).subscribe((data) …Run Code Online (Sandbox Code Playgroud)