Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

filterNil() not working with FormControl correctly? #481

Open
dertuerke opened this issue Aug 9, 2024 · 1 comment
Open

filterNil() not working with FormControl correctly? #481

dertuerke opened this issue Aug 9, 2024 · 1 comment

Comments

@dertuerke
Copy link

dertuerke commented Aug 9, 2024

Hi, why vscode says that "orderBy" can be null?

sortParamsForm = new FormGroup({
  orderBy: new FormControl<ESyncOrderBy>(ESyncOrderBy.Name),
  orderSequence: new FormControl<EOrderSequence>(EOrderSequence.Ascending)
});

// (property) orderBy: FormControl<ESyncOrderBy | null>
this.sortParamsForm.controls.orderBy.valueChanges
  .pipe(
      filterNil(),
      takeUntilDestroyed()
  ).subscribe((orderBy) => {
  // (parameter) orderBy: NonNullable<ESyncOrderBy | null>
  this.syncListStore.updateQuery({ orderBy });
});
@msmallest
Copy link

msmallest commented Aug 9, 2024

edit: I missed the entire point that I would assume filterNil would handle that. Sorry.

https://angular.dev/guide/forms/typed-forms#formbuilder-and-nonnullableformbuilder`

By default, Angular form controls when you call .reset will revert to null. So since the control could be reset, the controls will include null.

Starting in Angular 14, there is now 3 ways you can prevent this

  1. The closest to your way, new FormControl<ESyncOrderBy>(ESyncOrderBy.Name, { nonNullable: true })
  2. Using an instance of FormBuilder, like fb = inject(FormBuilder) you can do this.fb.nonNullable.control(...)
  3. Using an instance of NonNullableFormBuilder, like fb = inject(NonNullableFormBuilder) you can do this.fb.control(...).

This can be done on individual controls, so that should be sufficient for your use case. One thing to note: this cannot be done to a whole FormGroup instance, but you can make each control inside of it non-nullable.

edit:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants