[SOLVED] Create Observable from multiple FormControl

Issue

I have an Observable<FormGroup> that has a couple of boolean FormControl

readonly someForm$ = model$.pipe(map((model: Model) => {
  return new FormGroup({
    foo: new FormControl(model.getFoo()),
    bar: new FormControl(model.getBar()),
  });
}));

I would like to create an observable that emits if any of the FormControl values are true. I tried the following

readonly result$ = someForm$.pipe(switchMap(
  form => form.valueChanges.pipe(
    map(changes => changes.foo || changes.bar),
    startWith(() => form.value['foo'] || form.value['bar'])
  )
));

Though result$ always resolves to true during testing. What is the proper way to create an observable that is essentially foo || bar?

Minimal example: https://stackblitz.com/edit/angular-material-bvy7bj

Solution

There’re several issues:

  • You have result$ in your component and $result in your template.

  • startWith() doesn’t accept a function, it needs to be a value in your use-case.

  • You make two subscriptions to someForm$ which creates two unrelated FormGroup instances. You’ll need to use shareReplay(1) at the end of someForm$.

Your updated demo: https://stackblitz.com/edit/angular-material-xpqmcs?file=app%2Fapp.component.ts

Answered By – martin

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *