Grouping together multiple control value changes

1.2k views Asked by At

autocomplete functionality to trigger a filter function for each form control respectively.

Is there a way to group the statements instead of individually using multiple observables and separately writing them down as I did below?

this.filteredTypesCodes = this.assetTypeCodeControl.valueChanges
      .pipe(
        startWith(''),
        map(value => value.length >= 2 ? this._filter(value) : [])
      );

    this.filteredSubTypesCodes = this.assetSubTypeCodeControl.valueChanges
      .pipe(
        startWith(''),
        map(value => value.length >= 2 ? this._filter(value) : [])
      );

    this.filteredMakesCodes = this.assetMakeCodeControl.valueChanges
      .pipe(
        startWith(''),
        map(value => value.length >= 2 ? this._filter(value) : [])
      );
1

There are 1 answers

0
Elmehdi On BEST ANSWER

You have merge from Rxjs to merge multiple observables into one, but I don't think it will work for you, because you need each observable separately, what you can do instead, to stop repeating yourself is you can put the repeated code in a separate function, like so:

createFilter(formControl) {
      return formControl.valueChanges
      .pipe(
        startWith(''),
        map(value => value.length >= 2 ? this._filter(value) : [])
      );
}

Then you can use it to create your filters:

this.filteredTypesCodes = this.createFilter(this.assetTypeCodeControl)
this.filteredSubTypesCodes = this.createFilter(this.assetSubTypeCodeControl)
this.filteredMakesCodes = this.createFilter(this.assetMakeCodeControl)