Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen to blur event on a whole FormGroup in a reactive form

Tags:

angular

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?

like image 653
Esso Avatar asked Aug 30 '18 16:08

Esso


People also ask

What is a blur event Angular?

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.

What is FormBuilder in reactive forms?

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.


1 Answers

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' });
like image 50
Octavio Garbarino Avatar answered Oct 13 '22 03:10

Octavio Garbarino