如果FormControl为'',为什么FormGroup.Get返回null在名字里?

问题描述

问题: 我已经使用formGroup创建了一个formbuilder。 FormGroup具有名称中带有.的控件。现在,当我尝试使用formControl方法获取formGroup.get时,它将返回 null

代码

export class AppComponent implements OnInit  {
  name = 'Angular';
  obj = {};
  formGroup: FormGroup;

  constructor(private formBuilder: FormBuilder) {

  }

  ngOnInit() {
    this.obj["parent.child"] = new FormControl();
    this.obj["parent"] = new FormControl();

    this.formGroup = this.formBuilder.group(this.obj);

    // All controls
    console.log(this.formGroup.controls);

    // This is the problem its not geting the form control if I have '.' in the name of form control.
    console.log(this.formGroup.get("parent.child"));

    // If I am getting formControl without '.' then it is returning correctly.
    console.log(this.formGroup.get("parent"));
  }
}

这里有一个stackbiltz示例:https://stackblitz.com/edit/angular-grjh7e?file=src/app/app.component.ts

解决方法

使用FormGroup.get()时,它将使用“。”进行搜索。作为键分隔符,因此它将首先尝试找到控件“ cz”,但由于它不存在而失败(返回null)。

提供点分隔的字符串时,此函数的期望是这样的:

{
    "cz": {
        "datalite": {
            "makro": { ... }
        }
    }
}

解决方案:

this.formGroup.get(["parent.child"]);

工作示例:https://stackblitz.com/edit/angular-grjh7e?file=src/app/app.component.ts