7

Say I have a form:-

searchForm = new FormGroup({
      SearchBox = new FormControl<string>('', {nonNullable: true});
)}

And I try to do this:-

this.Query = this.searchForm.SearchBox.value;

The type of the Query property is a string, I get the error.

"Type 'string | undefined' is not assignable to type 'string'".

I can use the ! operator to make it work like so.

this.Query = this.searchForm.SearchBox.value!;

But is this the best way to tell it that the form control won't be undefined? Is there a better way to do this rather than slapping ! everywhere I want to assign the value of a form control to a property in the component?

Sham Dhiman
  • 1,348
  • 1
  • 21
  • 59
orangejuice
  • 183
  • 1
  • 13

1 Answers1

7

The type undefined is added because if the control is disabled, it’ll not be included in the value object. Read more on the angular docs here.

If you want to access the value including disabled controls, and thus bypass possible undefined fields, you can use searchForm.getRawValue()

Jayme
  • 1,776
  • 10
  • 28