Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make form model update on blur in angular 2

Is there an equivalent to this in angular 2?

ng-model-options="{ updateOn: 'blur' }"

Thanks

like image 886
matthewdaniel Avatar asked Nov 27 '15 23:11

matthewdaniel


People also ask

What is Updateon in angular?

Post Editor. When using Angular Forms, by default, on every keystroke, the values of your form controls are updated and their associated validators are executed.

What is the use of PatchValue in angular?

The PatchValue is used to update only a subset of the elements of the FormGroup or FormArray . It will only update the matching objects and ignores the rest.


2 Answers

In Angular 2 you can use the native DOM events

<input (blur)="someMethod()" />

Now, just define a method that does what you need when the field is blurred

like image 110
TGH Avatar answered Oct 13 '22 20:10

TGH


Even though this is a very old thread, there is now a very neat solution which comes with Angular5.

You trigger the update on blur like this:

Tempalte driven forms:

<input [(ngModel)]="lastname" [ngModelOptions]="{ updateOn: 'blur' }">

Reactive forms:

this.nameForm = new FormGroup ({
  firstname: new FormControl('', {
    validators: Validators.required,
    updateOn: 'submit'
  }),
  lastname: new FormControl('', {
    validators: Validators.required,
    updateOn: 'submit'
  })
});

(you can select submit or blur as values)

Reference: https://medium.com/codingthesmartway-com-blog/angular-5-forms-update-9587c3735cd3

like image 38
dave0688 Avatar answered Oct 13 '22 20:10

dave0688