问题
I need to iterate through all controls in Formbuilder, and children formbuilders to clear validators and updateValueAndValidity. How can I update answer from here to do so ?
Angular 2: Iterate over reactive form controls
Object.keys(this.form.controls).forEach(key => {
this.form.controls[key].clearValidators();
this.form.controls[key].updateValueAndValidity();
});
This form here has formbuilders within formbuilders, etc. The answer above only affects top level children, not subchildren, etc
this.editSharedForm = this.formBuilder.group({
'name': [null, [Validators.maxLength(50)]],
'streetAddress': [null, [Validators.maxLength(50)]],
'city': [null, [Validators.required,Validators.maxLength(200)]],
'zipcode': [null, [Validators.maxLength(10)]],
'phoneNumber': [null, [Validators.maxLength(50)]],
'emailAddress': [null, [Validators.maxLength(50), Validators.email]],
'addressChangeReason': this.formBuilder.group({
'addressChangeReasonId': [null, [Validators.required, Validators.min(1)]],
'addressChangeReasonCode': [null, [Validators.required, Validators.maxLength(50)]],
'addressChangeReasonDescription': [null, [Validators.required, Validators.maxLength(255)]]
}),
'addressSource': this.formBuilder.group({
'sourceOfAddressId': [null, [Validators.required, validatorDropdown]],
'sourceOfAddressCode': [null, [Validators.required, Validators.maxLength(50)]],
'sourceOfAddressDescription': [Validators.required, Validators.maxLength(255)]]
})
});
}
2) Additionally, how can I just target 1 subchild (eg addressChange Reason) if needed ? Following is not working
Object.keys(this.editSharedForm.get('addressChangeReason').controls).forEach(key => {
this.editSharedForm.controls[key].clearValidators();
this.editSharedForm.controls[key].updateValueAndValidity();
});
Property 'controls' does not exist on type 'AbstractControl'
回答1:
So, if you want to call clearValidators and updateValueAndValidity on every nested FormControl, you must loop through all nested FormGroups and FormArrays.
It's quite simple as you can see in this quick example:
clearValidators(formGroup: FormGroup| FormArray): void {
Object.keys(formGroup.controls).forEach(key => {
const control = formGroup.controls[key] as FormControl | FormGroup | FormArray;
if(control instanceof FormControl) {
console.log(`Clearing Validators of ${key}`);
control.clearValidators();
control.updateValueAndValidity()
} else if(control instanceof FormGroup || control instanceof FormArray) {
console.log(`control '${key}' is nested group or array. calling clearValidators recursively`);
this.clearValidators(control);
} else {
console.log("ignoring control")
}
});
For question 2)
Simply call
clearValidators(this.editSharedForm.get('addressChangeReason'))
https://stackblitz.com/edit/angular-dzsrq8
来源:https://stackoverflow.com/questions/59505578/angular-iterate-over-reactive-form-controls-and-subchildren-etc