Angular2 中反应形式的验证
Validation of reactive form in Angular2
我有反应形式:
protected _valueForm = this._formBuilder.group({
valueCaption: '',
});
protected _elementForm = this._formBuilder.group({
caption: ['', Validators.required],
required: [false]
});
然后在ngOnInit()
中有一个条件_elementForm
正在改变:
this._elementForm = this._formBuilder.group({
caption: ['', Validators.required],
required: false,
valueForm: this._valueForm,
values: this._formBuilder.array([])
},
{validator: FormElementValidator});
验证者:
export const FormElementValidator = (control: AbstractControl): ValidationErrors => {
const values = (control.get('values') as FormArray).value;
return (!!values.length) ? null : {noValues: 'T_FORM_VALUES_ARE_REQUIRED'};
}
效果很好,但是 elementForm
无效,如果 valueCaption
为空。为什么会这样,我该如何解决?
如果您不想要求它,为什么要添加 Validators.required
只需做类似
的事情
protected _elementForm = this._formBuilder.group({
caption: ['']
});
我有反应形式:
protected _valueForm = this._formBuilder.group({
valueCaption: '',
});
protected _elementForm = this._formBuilder.group({
caption: ['', Validators.required],
required: [false]
});
然后在ngOnInit()
中有一个条件_elementForm
正在改变:
this._elementForm = this._formBuilder.group({
caption: ['', Validators.required],
required: false,
valueForm: this._valueForm,
values: this._formBuilder.array([])
},
{validator: FormElementValidator});
验证者:
export const FormElementValidator = (control: AbstractControl): ValidationErrors => {
const values = (control.get('values') as FormArray).value;
return (!!values.length) ? null : {noValues: 'T_FORM_VALUES_ARE_REQUIRED'};
}
效果很好,但是 elementForm
无效,如果 valueCaption
为空。为什么会这样,我该如何解决?
如果您不想要求它,为什么要添加 Validators.required 只需做类似
的事情protected _elementForm = this._formBuilder.group({
caption: ['']
});