动态生成基于阵列的复选框列表并显示它们
问题描述:
我正在使用ReativeForms。我有一个数组,我想显示为复选框。这是我有:动态生成基于阵列的复选框列表并显示它们
dietaryRestrictionList由
- RestrictionType的:字符串=这应该是复选框
- 器isChecked的名字:它布尔=无论是检查还是不
在我的ngOnInit()我初始化我的数组。
this.healthInfoForm = this._fb.group(
{
dietaryRestrictionList: this._fb.array([]),
});
当我得到的数据我做一个for循环我设置的值:
> const control =
> <FormArray>this.healthInfoForm.controls['dietaryRestrictionList'];
> for(var i = 0; i < this.dietaryRestrictionList.length; i++){
> let checkBoxLabel = this.dietaryRestrictionList[i].RestrictionType;
> control.push(this._fb.group({
> checkBoxLabel: this.dietaryRestrictionList[i].IsChecked// set whether it's checked or not
> })) }
现在我想在HTML页面来显示这一点:
<div formArrayName="dietaryRestrictionList" class="form-group">
<div *ngFor="let diet of healthInfoForm.controls.dietaryRestrictionList.controls; let i=index" >
<div [formGroupName]="i">
<label>
<input type="checkbox" [formControl]="let diet of healthInfoForm.controls.[diet.boxName]" class="form-control">
</label>
</div>
</div>
</div>
我试图遵循这个例子:https://scotch.io/tutorials/angular-2-form-validation
事情不起作用。我收到一条错误消息,内容如下:
Unhandled Promise rejection: Template parse errors:
Parser Error: Unexpected token let at column 1 in [let diet of
healthInfoForm.controls.[diet.boxName]] in [email protected]:53 ("
<label><input type="checkbox" [ERROR ->][formControl]="let diet of healthInfoForm.controls.[diet.boxName]" class="form-control">"): [email protected]:53
我该如何获得此功能?
答
Becasue不能使用angular2的let
局部变量里面formControl
,你必须做这样来实现这一目标
<div formArrayName="dietaryRestrictionList" class="form-group">
<div *ngFor="let diet of healthInfoForm.controls.dietaryRestrictionList.controls; let i=index" >
<div [formGroupName]="i">
<label>
<input type="checkbox" [formControl]="diet[i]" class="form-control">
</label>
</div>
</div>
</div>
我得到了进一步的错误,现在,说:联模板:270:55引起的:不能找到控制与未指定的名称属性 – SmokerJones
是因为你动态提供的控制名称不存在于你的组件的任何地方,所以抛出这个错误,我认为你需要在这种情况下使用formarray –
我不太明白。我正在使用FormArray。 – SmokerJones