Search code examples
angularformstypescriptangular-forms

NgModel update on both onBlur & onSubmit


I am trying to create a form with inputs that only update onBlur ([ngFormOptions]="{updateOn: 'blur'}"). But a side effect of this is that the form is no longer submitted once the user hits 'enter', since the model is only updated onBlur. (same as this question, but it has no answer)

As a result of this the form is marked invalid, since there is a value in the input field, but the model is not yet updated with the value.

Versions: - Angular 6.0.7 - @angular/forms 6.0.7


HTML example

<form (ngSubmit)="login()" #loginForm="ngForm" [ngFormOptions]="{updateOn: 'blur'}" [validate-on-submit]="loginForm">
  <input type="text" ([NgModel])="user.username"/>
  <input type="password" ([NgModel])="user.password"/>
</form>

When entered a valid text in both fields and hitting 'enter', the form validates and marks password (the input that had the focus) as invalid, since the NgModel has not yet been updated, and thus the value is invalid.


What do I want

So what I am looking for is a way to validate on both onBlur aswell as onSubmit. I know that since Angular 5 we have the option [ngFormOptions]="{updateOn: 'blur'}", but is there a way to give 2 parameters to this object?

([ngFormOptions]="{updateOn: ['blur', 'submit']}" doesn't seem to work)

Almost forgot, I do not want the model updated onChange (creates annoying messages that are not very helpfull, since the user is still typing..)


Solution

  • Create a third, invisible input in your form, and give it a template variable. Before submitting, simply focus this input, which will trigger the onBlur update :

    <form (ngSubmit)="focuser.focus(); login()" #loginForm="ngForm" [ngFormOptions]="{updateOn: 'blur'}">
      <input type="text" ([NgModel])="user.username"/>
      <input type="password" ([NgModel])="user.password"/>
      <input type="hidden" #focuser>
    </form>
    

    Note that this is one of the many workarounds you can use, not an actual solution