2017-03-06 119 views
0

我正在使用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 

我該如何獲得此功能?

回答

1

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> 
+0

我得到了進一步的錯誤,現在,說:聯模板:270:55引起的:不能找到控制與未指定的名稱屬性 – SmokerJones

+0

是因爲你動態提供的控制名稱不存在於你的組件的任何地方,所以拋出這個錯誤,我認爲你需要在這種情況下使用formarray –

+0

我不太明白。我正在使用FormArray。 – SmokerJones