Reputation: 1205
Given valueChanges listener with Angular Reactive Forms
this.companyForm.valueChanges.subscribe((value) => {
console.log('setChangesListener value', value);
});
How do I find which field was changed exactly?
Upvotes: 3
Views: 2873
Reputation: 79
If we need to listen to a specific field that is changed instead of the entire form, we usually break it up in code. Granted, we usually don't need to check every field in the form being changed so we don't have to split up the listeners, but you could do it this way:
formControlOneAccessor: UntypedFormControl = new UntypedFormControl("");
formGroup: UntypedFormGroup = new UntypedFormGroup({
formControlOne: this.formControlOneAccessor,
formControlTwo: new UntypedFormControl("")
})
...
formControlOneAccessor.valueChanges.subscribe((value: any) => {
//logic you need to execute on your formControl change.
});
formGroup.valueChanges.subscribe((values: any) => {
//logic for skipping the form control item...
});
Upvotes: 0
Reputation: 3982
There's no way to see which field changed from the top level form subscription.
However, you can individually subscribe to form controls and that way you know exactly which field changed:
Object.entries(this.formGroup.controls).forEach(value => {
const [key, control] = value;
control.valueChanges.subscribe(
(val) => {
console.log(key, val);
},
);
});
Upvotes: 4
Reputation: 668
as per angular documents
you can check for form controls with dirty
flag true
this.formGroup.valueChanges.subscribe(val =>
console.log(
Object.keys(this.formGroup.controls).filter(
item => item.value.dirty
)
);
);
the console output is an array of strings with controls whose values have changed
I think this is the best solution
Upvotes: 0
Reputation: 106
For detecting changes in value of a particular field, 'valueChanges' event on that field can be subscribed, as shown below:
this.formGroup.controls['FieldName'].valueChanges.subscribe(change => {
console.log(change);
});
Upvotes: 0
Reputation: 101
The better option is to subscribe valuechange in form control rather than doing it on formGroup, this way you don't need to check for the field.
this.formGroup.get('formControlName').valueChanges.subscribe(val => {
console.log(value)
});
If you need to capture keychange event, you can bind keyup or keydown event in your template with a function call.
<input type="text" (keyup)="handleKeyUpEvent($event)"/>
Upvotes: 0