问题描述
我正在尝试为FormControl mealType
I'm trying to make a custom validator for my FormControl mealType
如果我的FormControl category
具有值而mealType
没有值,则mealType
应该无效.
If my FormControl category
has a value and mealType
does not, mealType
should be invalid.
如果category
没有值,则mealType
应该有效.
If category
has no value, mealType
should be valid.
我收到控制台错误:
代码:
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
}
}
但这会导致:
尝试一下:
class MealTypeValidator {
constructor(private categoryFormControl: FormControl) { }
mealTypeValidator(control: FormControl): { [error: string]: any } {
if (this.categoryFormControl.value) {
if (!control.value) {
return { error: true };
}
}
}
}
然后在我的表单组件中:
then in my form component:
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,
});
}
但是我有编译错误.我该如何正确处理?我认为我所做的验证类及其用法都还差一点.
but I have compilation errors. How do I get this right? I think i'm just a bit off on both the validation class I made and the usage of it.
推荐答案
您又近了一步.
您需要将自定义验证器附加到FormGroup
,因为它需要知道两个FormControl
(categories
和mealTypes
),因此附加到FormGroup
将为验证器提供更广阔的视野和访问整个FormControl
You need to attach your custom validator to the FormGroup
instead, because it needs to know two FormControl
(categories
and mealTypes
), so attaching to FormGroup
will give the validator more broad view and access to the entire FormControl
要实现该目标,请将您的ngOnInit
更改为
To achieve that, change your ngOnInit
to
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
,因此您可以在参数中附加自定义验证.另外,将自定义验证器移动到组件类之外.
On above code, you actually have to use FormGroup
constructor instead of FormBuilder
, so you can attach your custom validation in the parameters. Also, move your custom validator outside the component class.
请查看此柱塞,以便在此处了解您的具体情况.
Take a look at this Plunker to get more insight for your specific case here.
这篇关于依赖于另一个表单控件的Angular 2自定义验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!