0
votes

Hi All, I have a table, where each row is a FormGroup(a form), and the row columns is a FormControl(a data input field). All FormGroup (table rows) in a FormArray. I have no submit button, when something changed I should save that row which changed. As we know, if the field is a text input, the .valueChange is triggering at every character type. I guess probably need to use debounceTime(500) or/and distinctUntilChanged(), to prevent triggering the change before the user stopped the typing. One more thing, probably I need to use .merge or .combineLatest to collect the field changes of the row. My question is, how can I set the debounce time, globally to the input FormControl of the FormGroup of the FormArray? What need to listening, so which object valueChanges should be listening? I guess the FormArray items, the FormGroup.

I thinking on something similar, probably I will resolve this on RxJS way

const field1Observable = <Observable>rowFormGroup.get('field1').valueChanges;

const field2Observable = <Observable>rowFormGroup.get('field2').valueChanges.debounceTime(500);

const field3Observable = <Observable>rowFormGroup.get('field3').valueChanges;

const field4Observable = <Observable>rowFormGroup.get('field4').valueChanges.debounceTime(500);

const field5Observable = <Observable>rowFormGroup.get('field5').valueChanges;

const combinedRowObservable = Observable.combineLatest( [field1Observable, field2Observable, field3Observable, field4Observable, field5Observable ] ); combinedRowObservable.subscribe(( [ f1, f2, f3, f4, f5 ] ) => { this._logger.info('f1 ' + f1); this._logger.info('f2 ' + f2); this._logger.info('f3 ' + f3); this._logger.info('f4 ' + f4); this._logger.info('f5 ' + f5); });

this.combinedObservables.push(combinedRowObservable);

The observables should unsubscribe in ngOnDestroy

1

1 Answers

0
votes

you can do something like this and call the form element by id:

import { fromEvent } from 'rxjs';
import { debounceTime, map } from 'rxjs/operators';

// elem ref
const searchBox = document.getElementById('search');

// streams
const keyup$ = fromEvent(searchBox, 'keyup');

// wait .5s between keyups to emit current value
keyup$
  .pipe(
    map((i: any) => i.currentTarget.value),
    debounceTime(500)
  )
  .subscribe(console.log);

globally is in the use so be careful adding debounce time all over the place can cause unwanted slugishness - most forms are stateful - so this is really an acceptation to the rule for your particular use case.