5
votes

How to get parent form group in a nested form group for a control. At the time of validation of a control, i need a sibling control value. Both these controls are part of formgroup, which is part of formArray. I know we have root, which gives the root element. How can I get immediate parent of a given form control.

2
In your case it should be the FormGroup's responsibility to validate one control's value by referring to another one's.Harry Ninh

2 Answers

11
votes

You can access the parent of a given FormControl with .parent the same way you would be using .root.

Here's the doc: https://angular.io/api/forms/AbstractControl#parent

4
votes

I had the same problem. We have a nested form group like this:

FormGroup1:
 - FormControl1
 - FormControl2
 - FormGroup2
   - FormControl3
   - FormControl4

So in the custom validator for FormGroup2.FormControl3 you can find the root which is FormGroup1 like this:

export class CustomValidator {
    static FormControl3Valid() {
    return function (input: FormControl) {
      if (!input.root || !input.parent) {
        return null;
      }

      const root = input.root as FormGroup;

      if (root.get('FormControl1').value === 'someValue1' &&
        root.get('FormGroup2').get('FormControl4').value === 'someValue2') {
        return { 'required': true };
      }

      return null;
    };
  }
}

Just remember that this piece of code makes all the difference:

if (!input.root || !input.parent) {
   return null;
}

You have to check that the FormGroups are created before navigating to root or parent.