我从API调用中返回以下对象:
"users": [
{
"id": 1,
"name": "John",
"email": "john@company",
"created_at": "2016-09-08 03:53:43",
"updated_at": "2016-09-09 15:05:13",
"company_status": {
"status": "1"
}
},
{
"id": 2,
"name": "Moderator",
"email": "mod@company.com",
"created_at": "2016-09-08 15:26:20",
"updated_at": "2016-09-08 15:26:25",
"company_status": {
"status": "0"
}
}
]
我试图循环创建动态表单输入,如下所示:
<tr *ngFor="let user of users">
<td><input formControlName="user_name" class="form-control" type="text" name="user_name"></td>
<td><input formControlName="user_email" class="form-control" type="text" name="user_email"></td>
<td>
<div class="input-switch">
<input [attr.id]="'toggle_' + user.id" [formControlName]="'user_status_' + user.id" class="toggle" type="checkbox" value="{{ user.company_status.status }}">
<label [attr.for]="'toggle_' + user.id" class="input-toggle-xs"></label>
</div>
</td>
</tr>
但是在我对组件的ngOnIit方法中,我最初是这样构建的:
ngOnInit() {
// Build the form
this.companyForm = this.formBuilder.group({
'user_name' : ['', Validators.required],
'user_email' : ['', Validators.required]
});
}
由于用户状态输入是动态生成的,表单生成器不知道它们,我收到以下错误:
EXCEPTION: Error in edit.template.html:74:87 caused by: Cannot find control with name: 'user_status_1'
目前Angular 2中是否可以生成动态输入,以便我的表单可以看到它们并跟踪值?
答案 0 :(得分:3)
您应该在formBuilder.group
中创建一个日期名称,您可以使用:
ngOnInit() {
// Build the form
for(let item in users){
this.companyForm = this.formBuilder.group({
['user_name' + item.id] : ['', Validators.required],
['user_email' + item.id] : ['', Validators.required]
});
}
}