TransWikia.com

Dynamic parameters startWith Rxjs

Stack Overflow Asked by luden on January 1, 2021

I wish to addition emmited values of multiples input fields when a values changes.

The problem is : There is multiple fields and i wish it dynamic because i don’t know how many fields i can have in advance !

// In this case i have 3 input fields 
var keyObjectFields = ["0", "1", "2"];


const observedValues = keyObjectFields.map(key => this.credentialsForm.controls[key].valueChanges
    .map(value => +value).startWith(0, 0, 0))

const resSurface = combineLatest(observedValues)
    .pipe(map(([value0, value1, value2]) => { return value0 + value1 + value2 }));

resSurface.subscribe(val => { this.surface = val });

One Answer

Use startWith(0) to start each observable with 0. Use array.reduce to calculate the sum of an array.

// In this case i have 3 input fields 
var keyObjectFields = ["0", "1", "2"];


const observedValues = keyObjectFields.map(
  key => this.credentialsForm.controls[key].valueChanges.pipe(
    map(value => +value),
    startWith(0)
  )
);

const resSurface = combineLatest(observedValues).pipe(
  map(values => values.reduce((sum, curr) => sum + curr))
);

resSurface.subscribe(val => { this.surface = val });

Answered by fridoo on January 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP