Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update form values both on blur and submit in Angular

I am implementing a reactive form in Angular 5, and I need to trigger validation in both events, when the fields are blurred and also when the form is submitted.

I have set it to blur using the updateOn property to 'blur', but if you are focused on a field and press enter, the blur event is not triggered, and the value of the field is not updated, unless I click away from the field.

As far as I know there is no way of settingn updateOn to both blur and submit.

Is there any way of achieving this?

like image 739
MartaGalve Avatar asked Feb 06 '18 05:02

MartaGalve


People also ask

Which method is used to update the form values in Angular?

Updating Form controls from a model is very easy and flexible in Reactive Form API of Angular v2. So, setValue() and patchValue() are the methods by which we can update the Reactive forms controls from our model.

What is Updateon in Angular?

When using Angular Forms, by default, on every keystroke, the values of your form controls are updated and their associated validators are executed. This may not be always desirable.

What is the use of SetValue in Angular?

setValue()linkSets a new value for the form control.

How do you clear form data after submit in Angular?

import { FormsModule } from '@angular/forms'; In Reactive forms, we need to import FormGroup from '@angular/forms' . After importing the above-mentioned modules in the respective approach, angular forms module provides an inbuilt method called reset(). We can use the method and we can reset the form.


1 Answers

The easiest way is to focus on some element when submitting. The more appropriate is submit button I think.

<form #form="ngForm" (ngSubmit)="submitBtn.focus(); submit()" [ngFormOptions]="{ updateOn: 'blur' }" novalidate>
  ...
  <button type="submit" #submitBtn>
</form>
like image 69
Dzmitry Vasilevsky Avatar answered Oct 08 '22 17:10

Dzmitry Vasilevsky