简体   繁体   中英

Dynamic parameters startWith Rxjs

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 });

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 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM