Nouman Bhatti
Nouman Bhatti

Reputation: 1421

Angular 4 : FormArray gives "ERROR TypeError: Cannot read property 'id' of undefined"

I've a requirement where I've to add checkboes at runtime on my page. I'm using Angular Reactive Forms approach. I can see a following error in browser console. checkboxes are added after the errors though

ERROR TypeError: Cannot read property 'id' of undefined

FormGroup declaration

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

Loading the permissions like this

//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 Code to display the checkboxes is

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

any suggestions what I'm doing wrong here?

Upvotes: 0

Views: 2490

Answers (1)

Nouman Bhatti
Nouman Bhatti

Reputation: 1421

I fixed the issue by initializing the licenseType class during the declaration. Initially the code is

licenseType: ILicenseType;

and I changed it to

licenseType: ILicenseType = new ILicenseType();

This Link helped me pointing it to this direction.

Upvotes: 1

Related Questions