我使用反应形式在Angular 2中创建了一个表单组。我是新手,所以如果问题毫无意义,我会事先道歉。我在父组中创建了一个嵌套组,该组具有自己的自定义验证器。在下面的代码片段中,嵌套组是customRolesGroup。验证器适用于嵌套表单组,但父表单有一个控件,该控件也调用相同的验证方法。我遇到的问题是,每当父控件调用验证方法时,我需要它自动将嵌套组错误设置为null或false。
无论如何,我可以将嵌套组控件从父控件传递给验证器(customRoleValidation),还是将嵌套的表单控件错误修补为空?
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;
}
}
}

答案 0 :(得分:2)
您可以从父控件而不是嵌套表单组调用 this.customRoleValidation 。在那里,您可以获得父控件和嵌套表单组控件。