2017-10-16 22 views
0

私は実行時に自分のページにチェックボックスを追加する必要があります。私はAngular Reactive Formsアプローチを使用しています。ブラウザのコンソールで次のエラーが表示されることがあります。チェックボックスは、チェックボックスを表示するには、この角4:FormArrayが "ERROR TypeError:未定義のID 'プロパティを読み取れません"

//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> 
あるように権限をロード

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([]) 
    }) 

しかしエラーの後に追加されます

ここで間違っていることは何ですか?

+1

私は 'licenseType'が非同期的にフェッチされると思います。したがって、 'this.licenseTypeService.getPermissions(this.licenseType.id)'を呼び出すと 'undefined 'になります。 – n00dl3

+0

私はこれについて何も指定しなかったが、データはエラーの後に読み込まれる –

答えて

0

宣言中にlicenseTypeクラスを初期化して問題を解決しました。 は、最初のコードは

licenseType: ILicenseType; 

であると私は

この Link
licenseType: ILicenseType = new ILicenseType(); 

にそれを変更し、この方向にそれを指している私を助けました。

関連する問題