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
});
You can use rxjs operators to check values.
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.
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.
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
});
//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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With