如何在Angle 4+中获取FormControl的完整路径

Nya*_*aha 4 typescript angular angular-reactive-forms angular-forms

如何在Angle 4+中获取FormControl的完整路径?

我有反应形式:

{
    name: '',
    address: {
        city: '',
        country: ''
    }
}
Run Code Online (Sandbox Code Playgroud)

而且我需要获得完整的控制权:

const addressFormGroup = this.form.get('address');
const cityControl = addressFormGroup.get('city');
cityControl.plsGiveMeFullPath() //address.city
Run Code Online (Sandbox Code Playgroud)

有没有现有的方法来获取cityControl的完整路径:FormGroup?

Mar*_*arc 5

我实现了这两种方法来获取此功能。

第一个是返回控件名称的助手(因为它在其父级中被索引)。该函数通过在其父controls对象上搜索等于您提供给它的控件的控件,然后返回键来实现。

第二个是递归函数,该函数使用上面的助手调用返回控件的名称,并为控件的父级调用自身,将返回字符串与点('。')相连。

  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;
    }

  }
Run Code Online (Sandbox Code Playgroud)