【发布时间】:2018-10-10 18:06:53
【问题描述】:
我在 Angular 2 中使用响应式表单创建了一个表单组。我对它很陌生,所以如果这个问题没有意义,我会提前道歉。我在具有自己的自定义验证器的父组中创建了一个嵌套组。在下面的代码 sn-p 中,嵌套组是 customRolesGroup。验证器适用于嵌套表单组,但父表单有一个控件,该控件也调用相同的验证方法。我遇到的问题是,每当父控件调用验证方法时,我需要它自动将嵌套组错误设置为 null 或 false。
我是否可以将嵌套组控件从父控件传递给验证器 (customRoleValidation) 或将嵌套表单控件错误修补为 null?
public createNewForm(event: string) : FormGroup {
this.addUserForm = this.fb.group({
firstName: ['',
[ Validators.required,
Validators.maxLength(AddUserConstants.maxLengthName)
]],
lastName: ['',
[ Validators.required,
Validators.maxLength(AddUserConstants.maxLengthName)]
],
email: ['',
[ Validators.required,
Validators.maxLength(AddUserConstants.maxLengthEmail),
Validators.pattern(AddUserConstants.emailPattern),
]],
roleSelection: [AddUserConstants.roleCustom,
[ Validators.required,
this.customRoleValidation
]],
admin: '',
customRolesGroup: this.fb.group({
salesPerson: '',
inventoryManager: '',
creativeReviewer: '',
reporter: '',
observer: '',
}, {validator: this.customRoleValidation}),
});
this.addEditButtonText = AddUserConstants.addUserCreateButton;
this.addEditDBCall = AddUserConstants.addEvent;
this.modalTitle = AddUserConstants.addUserTitle;
return this.addUserForm;
}
}
public customRoleValidation(c: AbstractControl) : {[key: string]: boolean} | null {
let rolesSelectedCounter : number = 0;
let noCustomRolesSelected : boolean;
Object.keys(c.value).map(function(key) {
if (c.value[key] == "" || c.value[key] == false) {
rolesSelectedCounter++;
}
rolesSelectedCounter == Object.keys(c.value).length ? noCustomRolesSelected = true : noCustomRolesSelected = false;
});
if (typeof c.parent !== 'undefined') {
if (noCustomRolesSelected && c.root.value.roleSelection == AddUserConstants.roleCustom) {
return { 'noCustomRoleSelected': true };
} else {
return null;
}
}
}
【问题讨论】:
标签: angular2-forms angular-reactive-forms