AnswerBun.com

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

Stack Overflow Asked by luden on January 1, 2021

1 Answers

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!

Related Questions

Find the best matching combination of numbers

0  Asked on December 18, 2020 by stkvtflw

     

toUpperCaseFunction does not work with await keyword

2  Asked on December 18, 2020 by goxarad784

   

How to split given linked list

1  Asked on December 18, 2020 by evgeni-nabokov

   

delete bigquery table from spark by using scala

1  Asked on December 17, 2020 by counter10000

     

Python : find_all() return an empty list

2  Asked on December 17, 2020 by bastien

     

expected false to deeply equal true on postman

2  Asked on December 17, 2020 by cristian-hernandez

   

Split the data in the specific column in the DataFrame

2  Asked on December 17, 2020 by jaehyeon-robert-han

   

preventDefault not working when form submit react js

2  Asked on December 17, 2020 by gihankumara

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved.