NgModel在onBlur& onSubmit [英] NgModel update on both onBlur & onSubmit

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

问题描述

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

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

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

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