Tim
Tim

Reputation: 1695

Angular 7 reactive form patchValue to null after an initial FormGroup fails

I have a FormGroup where the initial data may or may not be null. If it is null, the FormGroup will be built like:

this.dataForm = this.formBuilder.group({
    prop1: true,
    testGroup: this.formBuilder.group({
      data: null,
      check: { a: "a", b: "b"}
    })
});

If it is not null, it will be built like:

this.dataForm = this.formBuilder.group({
    prop1: true,
    testGroup: this.formBuilder.group({
      data: this.formBuilder.group({ x: 0, y: 1}),
      check: { a: "a", b: "b"}
    })
});

The problem comes if I try to set the value of data to null if it was not initially null.

I have set up a stackblitz here to demonstrate the problem. The error is:

can't convert null to object

Basically, the question is: Once a property has been set up as a FormGroup, how do you set it to null?

Upvotes: 0

Views: 7276

Answers (1)

DeborahK
DeborahK

Reputation: 60548

This: data: this.formBuilder.group({ x: 0, y: 1}), is defining another FormGroup. What does it mean to "set it to null"? You want to set x and y to null? Remove the FormGroup? I'm not sure what "set to null" means in the context of the FormGroup you are creating.

Assuming you mean to set the value of the FormControls in the FormGroup to null values, then this works:

changeToNull2() {
  console.log(this.dataForm2);
  console.log(this.dataForm2.get('testGroup').value);
  this.dataForm2.get('testGroup.data').patchValue({
    x: null,
    y: null
  });
}

If you mean to remove the FormGroup defined by data, you can use removeControl() like this:

  (<FormGroup>this.dataForm2.get('testGroup')).removeControl('data');

Updated stackblitz that shows both: https://stackblitz.com/edit/angular-7-reactive-form-validation-aeshez

UPDATE

Just to clarify, in this code:

this.dataForm = this.formBuilder.group({
    prop1: true,
    testGroup: this.formBuilder.group({
      data: null,
      check: { a: "a", b: "b"}
    })
});

data is a FormControl whose value is defaulting to null.

In this code:

this.dataForm = this.formBuilder.group({
    prop1: true,
    testGroup: this.formBuilder.group({
      data: this.formBuilder.group({ x: 0, y: 1}),
      check: { a: "a", b: "b"}
    })
});

data is a FormGroup with two FormControls: x with a default value of 0 and y with a default value of 1.

Upvotes: 2

Related Questions