【问题标题】:Why FormGroup.Get() returns null if FormControl have '.' in the name?如果 FormControl 有“。”,为什么 FormGroup.Get() 返回 null在名字里?
【发布时间】:2020-09-10 23:26:09
【问题描述】:

问题: 我使用formbuilder 创建了一个formGroup。 FormGroup 有一个名称中包含. 的控件。现在,当我尝试使用 formGroup.get 方法获取 formControl 时,它返回 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

【问题讨论】:

  • 请在您的问题中提供minimal, complete, reproducible example。通过将其包含在您的问题中,我们可以确保在外部链接不再可用时问题仍然有用。
  • @DavidWalschots 好的

标签: angular angular-reactive-forms formgroups


【解决方案1】:

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

当你提供一个点分隔的字符串时,这个函数的期望是这样的:

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

解决方案:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-15
    • 2022-12-26
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    相关资源
    最近更新 更多