动态生成基于数组的复选框列表并显示它们

时间:2017-03-06 10:03:45

标签: angular reactive-forms

我正在使用ReativeForms。我有一个数组的数组,我想显示为复选框。这就是我所拥有的:

dietRestrictionList由

组成
  • RestrictionType:string =应该是复选框的名称
  • IsChecked:boolean =是否已选中

在我的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 HealthInformationComponent@270:53 ("          
    <label><input type="checkbox" [ERROR ->][formControl]="let diet of healthInfoForm.controls.[diet.boxName]" class="form-control">"): HealthInformationComponent@270:53

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:1)

但是你不能在let内使用{2}的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>