2017-10-16 127 views
0

我有一個要求,我必須在運行時在我的頁面上添加checkboes。我正在使用Angular Reactive Forms的方法。我可以在瀏覽器控制檯中看到以下錯誤。複選框被錯誤後添加雖然Angular 4:FormArray給出了「ERROR TypeError:無法讀取未定義的屬性'id'

ERROR TypeError: Cannot read property 'id' of undefined

FormGroup聲明

this.licenseTypeForm = this.fb.group({ 
     name: ['', Validators.required], 
     description: '', 
     enabled: true, 
     deleted: true, 
     permissions: this.fb.array([]) 
    }) 

加載這樣

//Get Permissions 
getLicensePermission(): void { 
    this.licenseTypeService.getPermissions(this.licenseType.id) 
     .subscribe(
     (permissions: IPermissions[]) => this.onPermissionsRetrieved(permissions), 
     (error: any) => this.errorMessage = <any>error 
     ); 
} 

onPermissionsRetrieved(permissions: IPermissions[]): void { 
    if (this.permissionsArray == null) 
     this.permissionsArray = permissions; 

    var items = this.licenseTypeForm.get('permissions') as FormArray; 
    for (let permission of permissions) { 
     items.push(this.buildPermission(permission.code, permission.selected, permission.name)); 
    } 
} 

buildPermission(code: string, selected: boolean, name: string): FormGroup { 
    return this.fb.group({ 
     code: code, 
     selected: selected, 
     name: name 
    }); 
} 

Html代碼以顯示覆選框的權限是

<div class="form-group row"> 
      <label class="col-md-2 control-label">Permissions</label> 
      <!-- mark the formArray first --> 
      <div formArrayName="permissions" class="col-md-4 "> 
       <!-- here add the formGroupName, which is the index --> 
       <div *ngFor="let permission of licenseTypeForm.get('permissions').controls; let i=index " [formGroupName]="i" class="checkbox checkbox-circle checkbox-info"> 
        <input formControlName="selected" type="checkbox" id="{{'checkbox'+i}}" /> 
        <!-- use 'value' in between, since the 'name' is inside that object --> 
        <label attr.for="{{'checkbox'+i}}">{{permission?.value.name}}</label> 
       </div> 
      </div> 
     </div> 

有什麼建議我在這裏做錯了嗎?

+1

我猜'licenseType'是異步獲取的。所以當你調用'this.licenseTypeService.getPermissions(this.licenseType.id)'時,它是'undefined'。 – n00dl3

+0

我沒有爲此指定任何內容,但數據在錯誤之後加載 –

回答

0

我通過在聲明中初始化licenseType類來解決了這個問題。 最初的代碼是

licenseType: ILicenseType; 

,我把它改成

licenseType: ILicenseType = new ILicenseType(); 

Link幫我將其指向這個方向。

相關問題