shib jo
shib jo

Reputation: 37

Combine multiple form control observables and subscribe in a reactive form

I have a form with multiple input fields (Eg: CID,LastName,FirstName,etc.). Requirement is to give one input on form submit. So on entering input in any of the fields values in the fields other than the entered field needs to be cleared

Instead of subscribing valuechanges for all the controls I plan to use some operators in Rxjs to combine it and use only one subscribe. What I found is combineLatest. So I just pushed all the controls into an array and planned to pass to combineLatest operator.

I have created a stackblitz. https://stackblitz.com/edit/angular-xeqms6?file=src%2Fapp%2Fapp.component.ts

handleFormChanges(){

    const controlArr=[];
    for (const field in this.formControls) {
      controlArr.push(this.formEl.get(field).valueChanges);
    }

      combineLatest(controlArr)
       .pipe(map(control=>{
         startWith('')
        return control;
       }))
      .subscribe((value)=>{

        // Here I need to write the logic to clear input fields other than the current one.
        console.log(value);

      })
  }

Problem with the code above is that subscribe is first triggered only after values are entered in all the field at least once. Subsequent triggers are working as expected.

What I needed is on every valuechanges subscribe callback needs to be invoked

Upvotes: 1

Views: 3353

Answers (1)

Ezzabuzaid
Ezzabuzaid

Reputation: 568

  handleFormChanges() {
this.formEl.valueChanges
  .pipe(pairwise())
  .subscribe(([prev, current]) => {
    for (const field in prev) {
      if (prev[field] === current[field]) {
        this.formEl.get(field).setValue(null, { onlySelf: true });
      }
    }
  });

}

https://stackblitz.com/edit/angular-xeqms6

Upvotes: 3

Related Questions