Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Detect form changes

In Angular2 4.0 I have a FormGroup looking like this:

this.form = this._fb.group({
      a: ['', [Validators.required]],
      b: ['', [Validators.required]],
      c: ['', [Validators.required]],
    });

Is it possible to subscribe valueChanged on individual fields?

I dont want to detect changes on input c, so the below approach does not work:

this.form.valueChanges.debounceTime(400).subscribe(data => {
     // Do something
    });
like image 512
Vingtoft Avatar asked May 04 '17 22:05

Vingtoft


People also ask

How do you know if reactive form value is changed?

You can use rxjs operators to check values.

How does Angular check changes form?

In Angular we have observables which subscribe to form value changes. what you have to do is, subscribe to the form instance and detect any changes to the form. Suppose you don't want to include save button on your form. whenever user change any thing in the form save data to the server.

Which class is applied on a form control if its value is changed?

ng-touched will be applied if the condition is true and ng-untouched will be applied if false. This pair of classes defines the state of the control whether its value has been changed or not. ng-dirty will be applied if the condition is true and ng-pristine will be applied if false.


2 Answers

You can add separate subscriptions for FormControl a and b.

this.heroForm.controls["a"].valueChanges.subscribe(data => {
 // Do something
});

this.heroForm.controls["b"].valueChanges.subscribe(data => {
 // Do something
});
like image 133
tottomotto Avatar answered Oct 08 '22 12:10

tottomotto


  
//get form ref  
@ViewChild('myForm') myForm;

//implement afterview init to your class and use
// or you can use same code with ngOnInit

ngAfterViewInit(){
  this.myForm.valueChanges.debounceTime(500).subscribe(data =>            console.log('Form changes', data));
}

You can use this code, it will give you changed field data also.

like image 35
Sujith S Avatar answered Oct 08 '22 12:10

Sujith S