15

I listen to 2 forms via 2 [formControl] "toppings":array and "toppings2":array.

I must have the 2 values of the forms in the same time. So i combine my two observables with "CombineLatest"

My code:

ngOnInit() {
combineLatest(this.toppings.valueChanges, this.toppings2.valueChanges)
    .subscribe(val => console.log(val)) 
}

But now, in the initialisation of the component, only one form send console.log(val).

If i click on this form, after i receive log of my second form. Have you meet this problem ?

ggradnig
  • 13,119
  • 2
  • 37
  • 61
Newbiiiie
  • 1,401
  • 3
  • 14
  • 33
  • So you only get `console.log(val)` if you clicked on both forms at least one time? Remember, that `combineLatest` will not emit an initial value for an observable until each observable emits at least one value. – kedenk Sep 05 '18 at 09:36
  • yes in the bigining only one form send me valuechanges. If i click on it, the second can send me valuechanges after too.. Just i can't use the second form at first... – Newbiiiie Sep 05 '18 at 09:41

1 Answers1

38

You probably want to have an initial value for both Observables. combineLatest will only emit if all Observables have emitted at least one value. Use the startWith operator to create this behaviour, like this:

combineLatest(
    this.toppings.valueChanges.pipe(startWith("")), 
    this.toppings2.valueChanges.pipe(startWith("")))

Or, if you have initial values available, like suggested:

combineLatest(
    this.toppings.valueChanges.pipe(startWith(this.toppings.value)), 
    this.toppings2.valueChanges.pipe(startWith(this.toppings2.value)))

Note, that this will emit once with the initial values. To supress this behaviour, you can use the skip(1) operator to ignore this initial notification.

ggradnig
  • 13,119
  • 2
  • 37
  • 61