为什么 FormGroup.Get() 如果 FormControl 的名称中有 '.?



问题:我使用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"));
}
}

这里我有一个stackbitz示例: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

相关内容

最新更新