Angular Reactive Form 根据控件自动进行组验证
Angular Reactive Form Automatic Group Validation According to Controls
我不确定这是否是预期的行为;我有以下内容:
this.formGroup = this.fb.group({
name: this.fb.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required]
})
});
<div formGroupName="name">
<input type="text" formControlName="firstName">
<input type="text" formControlName="lastName">
</div>
当我提交表单和 console.log(this.formGroup)
时,name
AbstractControl
的 errors
对象为空。我预计它应该有一个 Object
和 required: true
。我哪里错了?
感谢@yurzui 指出相关的 issue -- 这是一个解决方法,将简单地检查两个控件:
import {AbstractControl} from '@angular/forms';
export const nameValidator = (control: AbstractControl): {[key: string]: boolean} => {
const firstName = control.get('firstName');
const lastName = control.get('lastName');
if (!firstName || !lastName) {
return null;
}
return firstName.value && lastName.value ? null : { required: true };
};
这当然需要作为验证器明确包含在内:
name: this.fb.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required]
}, {validator: nameValidator}),
我不确定这是否是预期的行为;我有以下内容:
this.formGroup = this.fb.group({
name: this.fb.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required]
})
});
<div formGroupName="name">
<input type="text" formControlName="firstName">
<input type="text" formControlName="lastName">
</div>
当我提交表单和 console.log(this.formGroup)
时,name
AbstractControl
的 errors
对象为空。我预计它应该有一个 Object
和 required: true
。我哪里错了?
感谢@yurzui 指出相关的 issue -- 这是一个解决方法,将简单地检查两个控件:
import {AbstractControl} from '@angular/forms';
export const nameValidator = (control: AbstractControl): {[key: string]: boolean} => {
const firstName = control.get('firstName');
const lastName = control.get('lastName');
if (!firstName || !lastName) {
return null;
}
return firstName.value && lastName.value ? null : { required: true };
};
这当然需要作为验证器明确包含在内:
name: this.fb.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required]
}, {validator: nameValidator}),