Joh*_*man 1 angular angular-reactive-forms formgroups
问题:
我创建了一个formGroupusing 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"));
}
}
Run Code Online (Sandbox Code Playgroud)
这里我有一个 stackbiltz 示例:https://stackblitz.com/edit/angular-grjh7e ?file=src/app/app.component.ts
使用时FormGroup.get()会使用“.”进行搜索。作为键分隔符,因此它将首先尝试查找控件“cz”并失败,因为它不存在(返回null)。
当您提供点分隔的字符串时,该函数期望的是:
{
"cz": {
"datalite": {
"makro": { ... }
}
}
}
Run Code Online (Sandbox Code Playgroud)
解决方案:
this.formGroup.get(["parent.child"]);
Run Code Online (Sandbox Code Playgroud)
工作示例:https ://stackblitz.com/edit/angular-grjh7e?file=src/app/app.component.ts
| 归档时间: |
|
| 查看次数: |
4864 次 |
| 最近记录: |