Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 384
Sun Avatar asked Mar 17 '26 10:03

Sun


2 Answers

You can reset the control:

  setForm2() {
    this.form.controls['address'].reset()
    this.form.patchValue({
        name: 'test'
      });
  } 
like image 122
Marcel Hoekstra Avatar answered Mar 18 '26 22:03

Marcel Hoekstra


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

like image 34
AT82 Avatar answered Mar 18 '26 22:03

AT82



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!