I am creating a large form, and I want to fire a notification and save data, each time the user exits a field (on blur). The problem is that I cannot find an observable for that event for the whole FormGroup. I now listen for value change, but that of course emits all the time. Example:
this.myForm.valueChanges.subscribe(() => {
this.saveFormData();
this.emitSaveNotification();
});
Controllers does not have any way of listening to blur neither, so I cannot loop this.myForm.controls
to add a subscription to the blur event.
Do I have to add a event listener to each element individually?
A blur event fires when an element has lost focus. Note: As the blur event is executed synchronously also during DOM manipulations (e.g. removing a focussed input), AngularJS executes the expression using scope. $evalAsync if the event is fired during an $apply to ensure a consistent state.
The FormBuilder service is an injectable provider that is provided with the reactive forms module. We will inject this dependency by adding it to the component constructor. File name : employeeDetails-editor.component.ts. 1constructor(private fb: FormBuilder) { } typescript.
A solution could be to add on the form the option {updateOn: 'blur'}
<form [ngFormOptions]="{updateOn: 'blur'}">
That will make that the value change will be triggered only when the user blur an input, not on every change, using this with your code should work
this.myForm.valueChanges.subscribe(() => {
this.saveFormData();
this.emitSaveNotification();
});
Edit 1 You can also add the updateOn option on the FormGroup creation if you are using model driven form:
this.nameForm = new FormGroup ({
onecontrol: new FormControl('', ),
othercontrol: new FormControl('', )
}, { updateOn: 'blur' });
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