[英]How to iterate over a formbuilder in Angular2?
I try to iterate over a form control but get some problem. 我尝试遍历窗体控件,但遇到了一些问题。 I use the FormBuilder from Angular2.
我使用Angular2中的FormBuilder。
I have following code in my controller: 我的控制器中有以下代码:
ngOnInit() {
let data = this.dataSet[this.key];
this.form = this._fb.group({});
Object.keys(data).forEach(name => {
this.form.addControl(name, new FormControl());
this.form.controls[name].setValue(data[name]);
});
console.log(this.form);
}
That gives the following output on the console: 这将在控制台上提供以下输出:
FormGroup
...
controls: Object
database1: FormControl
...
_value: Object
accessHost: "some host here"
accessKey: "the key here"
....
database2: FormControl
...
_value: Object
accessHost: "some host here"
accessKey: "the key here"
That looks OK for so far. 到目前为止看起来还可以。 the html code:
html代码:
<form [formGroup]="form" (ngSubmit)="onSave(form)">
<div *ngFor="let ups of form.controls | keyVal; let i=index">
{{ups.key}}
<div class="form-group">
<input class="form-control" formControlName="{{ups.key}}">
</div>
</div>
</form>
But this part is not working: 但是这部分不起作用:
<input class="form-control" formControlName="{{ups.key}}">
When I check the value of {{ups.key}}, that is "database1". 当我检查{{ups.key}}的值时,即为“ database1”。 Is "database1" in this case not a FormControlName?
在这种情况下,“ database1”不是FormControlName吗?
Thanks for Help 感谢帮助
You need to bind the formControlName attribute to an expression: 您需要将formControlName属性绑定到表达式:
<input class="form-control" [formControlName]="ups.key" />
Notice the [] arround the attribute. 注意[]环绕属性。 A good start is to take a look at this cookbook: Dynamic Form as suggested by @kcp
一个好的开始是看一下本食谱:@kcp建议的动态表单
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.