Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get full path of FormControl in angular 4+

How can I get the full path of FormControl in angular 4+?

I have the reactive form:

{
    name: '',
    address: {
        city: '',
        country: ''
    }
}

And I rly need to get full path of control:

const addressFormGroup = this.form.get('address');
const cityControl = addressFormGroup.get('city');
cityControl.plsGiveMeFullPath() //address.city

Is there existing method to get the full path of cityControl: FormControl | FormGroup?

like image 650
Nyahahahaha Avatar asked Jul 04 '18 13:07

Nyahahahaha


2 Answers

I implemented these two methods to get this functionality.

The first one is a helper that returns the name of a control (as it is indexed in its parent). The function achieves that by searching on its parent's controls object the control that equals the one that you gave it, and then returning the key.

The second one is a recursive function that calls returns the name of the control using the helper above and calls itself for the control's parent, joining the return string with dots ('.').

  getControlName(c: AbstractControl): string | null {
    if(!c.parent) return null;
    const formGroup = c.parent.controls;
    return Object.keys(formGroup).find(name => c === formGroup[name]) || null;
  }

  getControlPath(c: AbstractControl, path: string): string | null {
    path = this.getControlName(c) + path;

    if(c.parent && this.getControlName(c.parent)) {
      path = "."+path;
      return this.getControlPath(c.parent, path);
    } else {
      return path;
    }

  }
like image 96
Marc Avatar answered Sep 28 '22 07:09

Marc


@lonix Too long for a comment...

formGroup is either AbstractControl[] or { [key: string]: AbstractControl }, so just test for array and everything works as expected:

export const getControlName = (control: AbstractControl): string | null => {
  if (control.parent == null) {
    return null;
  }

  const children = control.parent.controls;

  if (Array.isArray(children)) {
    for (let index = 0; index < children.length; index++) {
      if (children[index] === control) {
        return `${index}`;
      }
    }
    return null;
  }

  return Object.keys(children).find(name => control === children[name]) || null;
};
like image 33
Lars Avatar answered Sep 28 '22 07:09

Lars