我有一系列产品返回给对象,这些对象看起来像:
{"opportunityId":2, "customer":"Graham's Motors",..."products":[{"id":1,"name":"Optoin 1","selected":false},{"id":2,"name":"Option 2","selected":false},{"id":3,"name":"Option 3","selected":true},...
我有一个导入的打字稿文件:
import { FormControl, FormGroup, FormArray } from '@angular/forms';
然后我创建一个这样的FormGroup:
opportunityForm = new FormGroup({
partner: new FormControl(''),
customer: new FormControl(''),
...
products: new FormArray([])
我正在使用API调用来填充数据,如下所示:
this.dataService.getOpportunity(this.id)
.subscribe(data => {
this.opportunityForm.setValue({
partner: data.partner ?? '',
customer: data.customer ?? '',
...
});
data.products.forEach(product => {
(<FormArray>this.opportunityForm.get('products')).push(new FormControl(product));
});
我认为正确地将产品作为表单数组放置。我的问题似乎是如何构造html。目前看起来像:
<div class="col" formArrayName="products">
<div *ngFor="let option of products; index as i" >
<label>
<input type="checkbox"
name="option.name"
value="{{option.value}}"
[formControlName]="i"
[checked]="option.selected"
(change)="option.selected = !option.selected"/>
{{option.name}}
</label>
</div>
</div>
我收到一条错误消息:
错误错误:必须为名称为'products'的表单控件提供一个值。
但是我看不到我在做什么错。谢谢你的帮助。我只想显示一个复选框列表,其中包含是否已选中它们(有一个编辑表单),然后允许用户对其进行更新,然后再将其发回表单。
答案 0 :(得分:0)
您需要将表单声明为组件的类成员:
export class HelloComponent implements OnInit {
opportunityForm;
ngOnInit() {
this.opportunityForm = new FormGroup({
partner: new FormControl(''),
customer: new FormControl(''),
products: new FormArray([])
});
}
}
然后您通过模板访问它:
<div class="col" formArrayName="opportunityForm.products">
<div *ngFor="let option of opportunityForm.products; index as i" >
....