2

Angular 14 introduced typed forms, which are amazing, but I'm struggling with a specific part of it: FormGroup.get(name) now appears to always return AbstractControl | null. How can I get it to be non-nullable?

Let's take a look at this FormGroup:

const form = new FormGroup({
  first: new FormControl('John'),
  last: new FormControl('Smith'),
});

When I access one of these controls via form.controls.first, the FormControl is known to exist and I have no issues accessing its value trivially:

enter image description here

However, when I use form.get('first'), the return value is always possibly null, adding a layer of complication I have to account for:

enter image description here

Now, Angular's FormControls are being more careful around FormControl.reset(), so their values can always be null unless you set { nonNullable: true }, like this:

new FormControl('John', { nonNullable: true });

However, there doesn't seem to be a corresponding explanation for why FormGroup.get() always returns a possibly-null value, and there doesn't seem to be any kind of nonNullable: true I can specify for FormGroups to ask it to guarantee the FormControl I request will be present. The difference between form.get('first') vs form.controls.first in terms of nullability is baffling to me.

What should I be doing with my FormGroups to ensure form.get(name) is non-nullable?

I understand I can use casts (form.get('first') as FormControl<string>) or non-null asserts (form.get('first')!) but those seem like they might be workarounds for a more core change I should be making in how I'm accessing or creating my forms.

doppelgreener
  • 4,809
  • 10
  • 46
  • 63

0 Answers0