我无法理解如何在Angular2表单中上传文件,该表单包含其他字段,同时验证此类文件的存在。
我需要validate
的文件输入,确实字段中有文件,因为此时angular2不会检测到该文件。到目前为止,我还没有找到关于如何验证angular2格式的文件输入的简明示例
以下片段是我的实际代码
的一个小假设示例在html模板中
<form [formGroup]="newCarRegistrationForm" (ngSubmit)="onSubmit(newCarRegistrationForm.value)">
<!-- ...other fieldsets -->
<fieldset class="fieldset" formGroupName="assets">
<legend class="text-5 legend">assets</legend>
<div formGroupName="thumbnails">
<div class="">
<input type="file"
formControlName="smallImage"
name="smallImage">
</div>
</div>
</fieldset>
<!-- ...other fieldsets -->
<button type="submit" [disabled]="!newCarRegistrationForm.valid" >Save</button>
</form>
在.ts组件
import {
Component, OnInit,
ElementRef, ViewChild
} from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: '...',
templateUrl: './...',
styleUrls: ['./...']
})
export class newCarRegistrationComponent implements OnInit {
public newCarRegistrationForm: FormGroup;
@ViewChild('fileinput') backgroundImage: ElementRef;
// public smallImage: string = '';
// public mediumImage: string = '';
// public largeImage: string = '';
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.initForm();
}
assignFileOnChange(event, formKey) {
this[formKey] = event.target.files[0].name;
console.log(event.target.files[0].name, this[formKey]);
}
onSubmit(value: any): void {
console.log(value);
}
initForm() {
this.newCarRegistrationForm = this.fb.group({
assets: this.fb.group({
thumbnails: this.fb.group({
smallImage: ['', Validators.required],
mediumImage: ['', Validators.required],
largeImage: ['', Validators.required]
})
})
})
}
}
感谢您的帮助