Let's say you're in a situation where you're listening to one FormControl but you're dependent on the value of another FormControl.
There are two elegant (in my opinion) solutions to this that I've come across.
Solution #1 - use withLatestFrom
withLatestFrom is an rxjs operator that, as the name suggests, lets you pull the latest value of whatever Observable(s) that you pipe in.
Here I am listening to the stream of field2 but the subscription is executed only when field1 has a value.
Solution #2 - use combineLatestWith
combineLatestWith is another rxjs operator that combines multiple streams and executes when any one of the Observables emit a value.
Both are useful in different scenarios
Here is what I mean by that -
With withLatestFrom, the subscription is executed only when field2 undergoes a value change and field1 has a value. So if you just change the value of field1, nothing happens.
With combineLatestWith, the subscription is executed when any of the controls undergo value changes. This can be problematic if you're running a lot of code in the subscription execution. So, use it with caution!
The videos below show what I mean.
If you want to try the code for yourself, it's up here on GitHub.
![Image that shows the following code block raw `<br>
this.form<br>
.get('field2')<br>
?.valueChanges.pipe(<br>
withLatestFrom(this.form.controls['field1']?.valueChanges)<br>
)<br>
.subscribe({<br>
next: ([field1, field2]) => {<br>
// Do something with field1 and field2<br>
},<br>
});<br>
` endraw](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9dab42wjlv2yzjwjwcx5.png)
![Image that shows the following code block raw `<br>
this.form.controls['field2'].valueChanges<br>
.pipe(combineLatestWith(this.form.controls['field1'].valueChanges))<br>
.subscribe({<br>
next: ([field1, field2]) => {<br>
// Do something with field1 and field2<br>
},<br>
});<br>
` endraw](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F98p5f49raamr7v1f9idg.png)
Top comments (0)