How to watch all FormControls ValueChanges except specific control?

后端 未结 4 1859
名媛妹妹
名媛妹妹 2021-01-12 10:33

I have a form that do a computation whenever a control input value changes.

Here is my form_group looks like:

form_group = this.fb.group         


        
相关标签:
4条回答
  • 2021-01-12 10:51

    Like so, I wanted to observe changes from multiple controls, I was able to do this like this.

    import { merge } from 'rxjs';
    ...
    const merged = merge(this.control1.valueChanges,this.control2.valueChanges, this.control3.valueChanges, this.control4.valueChanges);
    
    merged.subscribe(x => console.log(x));
    

    Reference:- https://rxjs-dev.firebaseapp.com/api/index/function/merge

    0 讨论(0)
  • 2021-01-12 10:54

    Is there a reason why you couldn’t create a FormArray instead of multiple form controls? For example

    form_group = this.fb.group({
        'controls': this.fb.array([...])
    });
    

    Then you can define a property in your component

    get controls(): FormArray {
        return <FormArray>this.form_group.get('control');
    }
    

    And then from this you can iterate the form array and subscribe to valueChanges

    this.controls.controls.forEach(control => {
        control.valueChanges.subscribe(...)
    });
    

    You can then apply some logic in the for each to exclude the controls you do not want to subscribe to

    0 讨论(0)
  • 2021-01-12 11:06

    You just need to access to the control and subscribe to value changes property like this

        this.form_group.get('control1').valueChanges.subscribe(value => {
            console.log(value)
        })
    
    0 讨论(0)
  • 2021-01-12 11:11

    You can merge individual valueChanges Observables into one like so :

    Observable.merge(
        [ control1.valueChanges,
          control2.valueChanges ]
      ).subscribe(() => {
        // do your computation
      });
    
    0 讨论(0)
提交回复
热议问题