onBlur & 上的 NgModel 更新提交时 [英] NgModel update on both onBlur & onSubmit

查看:33
本文介绍了onBlur & 上的 NgModel 更新提交时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用仅更新 onBlur ([ngFormOptions]="{updateOn: 'blur'}") 的输入创建表单.但这样做的一个副作用是,一旦用户点击输入",表单就不再提交,因为模型仅在模糊时更新.(与这个问题相同,但它没有答案)

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.

版本:- 角度 6.0.7- @angular/forms 6.0.7

Versions: - Angular 6.0.7 - @angular/forms 6.0.7

HTML 示例

<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>

当在两个字段中输入有效文本并点击回车"时,表单会验证并将密码(具有焦点的输入)标记为无效,因为 NgModel 尚未更新,因此该值无效.

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.

我想要什么

所以我正在寻找一种在 onBluronSubmit 上进行验证的方法.我知道从 Angular 5 开始我们有选项 [ngFormOptions]="{updateOn: 'blur'}",但是有没有办法给这个对象提供 2 个参数?

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']}" 似乎不起作用)

差点忘了,我想要更新模型onChange(创建烦人的消息,不是很有帮助,因为用户仍在打字..)

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

推荐答案

在表单中创建第三个不可见的输入,并为其提供一个模板变量.在提交之前,只需关注这个输入,这将触发 onBlur 更新:

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

这篇关于onBlur &amp; 上的 NgModel 更新提交时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆