Search code examples
angularangular-reactive-formsangular-forms

Null value in Angular Reactive form nested FormGroup


I have an angular reactive form with a nested form group

this.form = new FormGroup({
  name: new FormControl(),
  address: new FormGroup({
    line1: new FormControl(),
    line2: new FormControl()
  })
});

If I call form.patchValue with an object containing the nested fields everything works fine as expected:

this.form.patchValue({
    name: 'test',
    address: {
      line1: 'test line 1',
      line2: 'test line 2'
    }
  });

However if the address property is null:

this.form.patchValue({
    name: 'test',
    address: null
  });

I receive an error: Cannot convert undefined or null to object.

How can I get round this problem as the object returned from the server is valid and I have no control over it.

Example here: https://stackblitz.com/edit/angular-broncz

Thanks


Solution

  • You say you get an object from your server that you cannot control, so you don't know if address will have a value or not. You can use the || (or) operator for that.

    You can also reset the form just in case, depending on how you are using this. If form is not editable before patchValue, there would be no need to reset.

    // faking server response
    const myObj = { name: 'mytest', address: null };
    
    this.form.reset();
    this.form.patchValue({
      name: myObj.name,
      address: myObj.address || {}
    });
    

    STACKBLITZ