Home > Net >  Nullable nested FormGroup in Angular
Nullable nested FormGroup in Angular

Time:01-27

I have a FormGroup which has a nested FormGroup which I would like to be able to set to null:

this.myForm = formBuilder.group<MyForm>({
  foo: formBuilder.nonNullable.control<string>(''),
  group: new FormGroup<MyGroupForm | null>({
    bar: formBuilder.nonNullable.control('')
  })
});

Whenever I try to set the group to null like this:

this.myForm.setValue({
  foo: 'foo',
  group: null
});

I get the following error:

TypeError: Cannot read properties of null (reading 'bar')
  at forms.mjs:1594:18
  at forms.mjs:2818:24
  at Array.forEach (<anonymous>)
  at FormGroup._forEachChild (forms.mjs:2813:36)
  at assertAllValuesPresent (forms.mjs:1593:13)
  at FormGroup.setValue (forms.mjs:2670:9)
  at forms.mjs:2673:33
  at Array.forEach (<anonymous>)
  at FormGroup.setValue (forms.mjs:2671:28)
  at new AppComponent (app.component.ts:27:17)

This is not a duplicate of this question: Null value in Angular Reactive form nested FormGroup because I want intentionally set the group to null.

CodePudding user response:

It's a known issue since 2017 !

I proposed a PR recently, let see where this is going !

  • Related