【问题标题】:Angular 4 : FormArray gives "ERROR TypeError: Cannot read property 'id' of undefined"Angular 4:FormArray 给出“错误类型错误:无法读取未定义的属性 'id'”
【发布时间】:2017-10-17 06:44:56
【问题描述】:

我有一个要求,我必须在运行时在我的页面上添加 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>

有什么建议我在这里做错了吗?

【问题讨论】:

  • 我猜licenseType 是异步获取的。所以当你打电话给this.licenseTypeService.getPermissions(this.licenseType.id)时是undefined
  • 我没有为此指定任何内容,虽然数据是在错误之后加载的

标签: angular angular-reactive-forms


【解决方案1】:

我通过在声明期间初始化 licenseType 类解决了这个问题。 最初的代码是

licenseType: ILicenseType;

我把它改成了

licenseType: ILicenseType = new ILicenseType();

这个Link 帮助我指出了这个方向。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2021-11-05
    • 2018-04-10
    • 2021-04-22
    • 1970-01-01
    • 2020-07-22
    相关资源
    最近更新 更多