Angular 4:FormArray给出" ERROR TypeError:无法读取属性' id'未定义"

时间:2017-10-16 07:34:29

标签: angular angular-reactive-forms

我需要在我的页面上的运行时添加checkboes。我使用Angular Reactive Forms方法。我可以在浏览器控制台中看到以下错误。虽然

,但在错误之后添加了复选框
  

错误类型错误:无法读取属性' id'未定义的

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 个答案:

答案 0 :(得分:0)

我通过在声明期间初始化licenseType类来修复此问题。 最初代码是

licenseType: ILicenseType;

我将其改为

licenseType: ILicenseType = new ILicenseType();

Link帮我指出了这个方向。