角2自定义验证我试图做一个自定义的验证我的FormControl mealType
依赖于其他形式的控制
如果我FormControl category
具有价值和mealType
没有,mealType
应该是无效的。
如果category
没有值,mealType
应该是有效的。
我得到一个控制台错误:
TypeError: Cannot read property 'get' of undefined
代码:
ngOnInit() {
this.findForm = this.formBuilder.group({
categories: [null, Validators.required],
mealTypes: [null, this.validateMealType],
distanceNumber: null,
distanceUnit: 'kilometers',
keywords: null,
});
}
validateMealType() {
if (this.findForm.get('categories').value) {
if (this.findForm.get('mealTypes').value) {
var mealTypeError = false;
} else {
var mealTypeError = true;
}
} else {
var mealTypeError = false;
}
return mealTypeError ? null : {
error: true
}
}
这是我的形式,是不确定的。
我该如何解决这个问题?
尝试这样的:
validateMealType(categoryControl: FormControl, mealTypeControl: FormControl) {
if (categoryControl.value) {
if (!mealTypeControl.value) {
var mealTypeError = true;
} else {
var mealTypeError = false;
}
} else {
var mealTypeError = false;
}
return mealTypeError ? null : {
error: true
}
}
但它会导致:
Error in app/find-page/subcomponents/find-page/find-form.component.html:36:5 caused by: Cannot read property 'value' of undefined
尝试这样的:
class MealTypeValidator {
constructor(private categoryFormControl: FormControl) { }
mealTypeValidator(control: FormControl): { [error: string]: any } {
if (this.categoryFormControl.value) {
if (!control.value) {
return { error: true };
}
}
}
}
在我的表单组件
则:
ngOnInit() {
this.findForm = this.formBuilder.group({
categories: [null, Validators.required],
mealTypes: [null, new MealTypeValidator(this.findForm.get('categories').mealTypeValidator()],
distanceNumber: null,
distanceUnit: 'kilometers',
keywords: null,
});
}
但我有编译错误。我如何得到这个权利?我认为我对我所做的验证课和它的使用都有点偏差。
是否有可能有多个formgroup验证器?如果我想要另一个验证器,除了依赖于多个控件的“validateMealType”,该怎么办? –