Tolgon
Tolgon

Reputation: 33

Cannot read property 'value' of null angular reactive form get value

{
  "estimate_number": "2020-1234",
  "brand": "PF",
  "floor": "Laminaat",
  "floor_type": "Normaal",
  "plint_type": "Hoog",
  "floor_installer": {
    "id": "14",
    "name": "Maestro"
  },
  "address": {
    "street": "Straatnaam 19",
    "city": "Amsterdam",
    "postal_code": "1111AB",
    "province": "Noord-Holland"
  },
  "notes": "Test note"
}

why does const city = this.addEventForm.get('address.city').value; give me a value (in this case Amsterdam) but const floorInstaller = this.addEventForm.get('floor_installer.id').value; gives me the following error in developer console saying ERROR TypeError: Cannot read property 'value' of null at CalendarComponent.push..

This object is the result of a reactive angular form.

The FormBuilder code used to make up the form:

        // FormBuilder
        const datesGroup = this.fb.group({
            start_date: '',
            start_time: { hour: 7, minute: 30 },
            end_date: '',
            end_time: { hour: 17, minute: 30 },
        });

        const addressGroup = this.fb.group({
            street: '',
            city: '',
            postal_code: '',
            province: '',
        });

        this.addEventForm = this.fb.group({
            event_dates: datesGroup,
            estimate_number: '',
            brand: '',
            floor: '',
            floor_type: '',
            plint_type: '',
            floor_installer: { id: '', name: '', },
            address: addressGroup,
            notes: '',
        });

Upvotes: 1

Views: 8788

Answers (2)

Hi think you may get the value with below snippet:

this.addEventForm.get("address").get("city").value

Code snippet I tried:

const addressGroup = this.fb.group({
  city: ""
});

this.addEventForm = this.fb.group({
  address: this.fb.group({
    city: ""
  })
});
getVAlue() {
 console.log(this.addEventForm.get("address").get("city").value);
}

HTML:

<form [formGroup]="addEventForm">
 <div formGroupName="address">
    <input formControlName="city" >
 </div>
</form>
<button (click)="getVAlue()">Get</button>

Hope this will help. I just took only city. You may include all the controls.

Upvotes: 2

Barremian
Barremian

Reputation: 31125

May be the direct object { id: '', name: '', } isn't recognized by the get() function. Try assigning floor_installer it's own form builder group.

const floorInstallerGroup = this.fb.group({
  id: '',
  name: ''
});

this.addEventForm = this.fb.group({
.
.
.
  floor_installer: floorInstallerGroup,
.
.
}

Upvotes: 0

Related Questions