我有以下模式:
export interface Content {
lang: string;
title: string;
}我需要验证这个contents FormArray的parent FormGroup
this.formBuilder.group({
defaultLang: ['', Validators.required],
contents: this.formBuilder.array([], Validators.minLength(1))
});对于我的contents FormArray中的每个contents FormArray,我使用下面的content FormGroup验证模型
this.formBuilder.group({
lang: ['', Validators.required],
title: ['', Validators.required]
});现在,我将以下content FormGroup添加到我的contents FormArray中,以验证每个Content
(<FormArray>parentFormGroup.controls['contents'])
.push(this.contentFormGroup);但是使用这种方法,我无法验证这些规则:
Content字段被填充,那么就会发生内容验证(这意味着将content FormGroup添加到contents FormArray中)contents FormArray的contents FormArray)。lang of Content是parent FormGroup的defaultLang,那么内容是必需的。问题
是否需要使用验证器来添加/删除content FormGroup的contents FormArray?
是否有一种方法可以只使用角本机验证器?
我需要创建一个自定义验证器吗?如果是的话,您有什么很好的例子可以用FormArray来做吗?
发布于 2017-11-16 20:48:23
您可以向组中添加验证器,如下所示
this.group = this.formBuilder.group({
lang: ['', Validators.required],
title: ['', Validators.required]
});
this.group.setValidators([
this.titleRequiredValidator(),
]);
private titleRequiredValidator(): ValidatorFn {
return (group: FormGroup): { [key: string]: any } => {
const langControl = group.controls.lang;
const titleControl = group.controls.title;
if (langControl.value !== '' && titleControl.value == '')) {
const error = { required: true };
titleControl.setErrors(error);
return error;
}
else {
titleControl.setErrors(null);
return null;
}
};
}https://stackoverflow.com/questions/44432791
复制相似问题