我已经用FormArray创建了如下所述的表单
this.createModuleForm = this.fb.group({
artefactType: ['', Validators.required],
uploadDocuments: this.fb.array([]),
});
然后我将对象推入FormArray
formArray.push(this.fb.group({name: event.name, url: event.url, submittedBy: 'siva', role: this.currentUser.value.role}));
问题:如果uploadDocuments(FormArray)为空,则需要使Form无效,并且UploadDocuments应该是必填项
答案 0 :(得分:2)
创建自定义验证程序
我创建了minAdded函数,该函数将检查当前的formarray是否具有至少一个组
component.ts
this.createModuleForm = this.fb.group({
artefactType: 'De',
uploadDocuments: this.fb.array([], minAdded(1))
})
function minAdded(min = 1) {
const validator: ValidatorFn = (formArray: FormArray) => {
const minAdded = formArray.controls
.map(control => control.value).length;
return minAdded >= min ? null : { required: true };
};
return validator;
}
参考:https://coryrylan.com/blog/creating-a-dynamic-checkbox-list-in-angular 示例:https://stackblitz.com/edit/angular-dcy9z9