我正在尝试为我的 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
,因为它需要知道两个 FormControl
(categories
和 mealTypes
),因此附加到 FormGroup
将为验证器提供更广阔的视野并访问整个 FormControl
为此,将您的 ngOnInit
更改为
ngOnInit() {
this.findForm = new FormGroup({
mealTypes : new FormControl(null, Validators.Required),
categories : new FormControl(null)
// others form control here
}, validateMealType); // <-- see here is your custom function
}
在上面的代码中,您实际上必须使用 FormGroup
构造函数而不是 FormBuilder
,因此您可以在参数中附加自定义验证。此外,将您的自定义验证器移到组件类之外。
看看这个Plunker在此处获得对您的具体案例的更多见解。
关于依赖于另一个表单控件的 Angular 2 自定义验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40561221/