NgModel在onBlur和onSubmit

时间:2018-07-10 08:12:15

标签: angular forms typescript angular-forms

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

由于此结果,该表单被标记为无效,因为在输入字段中有一个值,但是尚未使用该值更新模型。

版本: -角度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尚未更新,因此该表单将密码(具有焦点的输入)验证并标记为无效,因此该值无效。


我想要什么

因此,我正在寻找一种同时在onBluronSubmit上进行验证的方法。我知道自Angular 5起,我们就有了[ngFormOptions]="{updateOn: 'blur'}"选项,但是有没有办法为这个对象赋予2个参数?

({[ngFormOptions]="{updateOn: ['blur', 'submit']}"似乎不起作用)

几乎忘记了,我不希望模型更新onChange(创建讨厌的消息,因为用户仍在键入,因此该消息不是很有帮助。)

2 个答案:

答案 0 :(得分:1)

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

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

请注意,这是您可以使用的许多解决方法之一,不是实际的解决方案

答案 1 :(得分:0)

解决方案-表单组件

在遵循@trichetriche的建议(创建一个保存表单逻辑的单独组件)并让模板驱动的表单偏向于响应式表单之后,我找到了以下解决方案:

@Component({
  selector: "val-message-form",
  templateUrl: "./message-form.html"
})
export class MessageFormComponent {

  /**
   * The form group that holds all the input fields and the logic of the input fields
   * @type {FormGroup}
   */
  @Input()
  public formGroup: FormGroup;

  /**
   * The function that will be called when the form is valid
   * The template that includes this component can listen to this event for the submit action
   * @type {EventEmitter}
   */
  @Output()
  private onSubmit = new EventEmitter();

  /**
   * Notify all listeners that the form has been submitted
   * NOTE: Notify will only work if the form is valid
   */
  public submitForm(): void {
    if (this.formGroup.valid) {
      this.onSubmit.emit();
    } else {
      this.updateControls(this.formGroup);
    }
  }

  /**
   * Recursively update all form controls, since we are going to display error messages
   */
  private updateControls(formGroup: FormGroup): void {
    Object.keys(formGroup.controls).forEach(field => {
      const control = formGroup.get(field);

      if (control instanceof FormControl) {
        control.markAsTouched({onlySelf: true}); // Otherwise validation color is not shown
        control.updateValueAndValidity({onlySelf: true})
      } else if (control instanceof FormGroup) {
        this.updateControls(control);
      }
    });
  }
}

请注意注入的表单组,我们可以在此组件中的新表单上进行设置,以便正确地嵌入表单控件(否则Angular无法识别表单控件)。 这是导致我无法使用模板驱动表单的问题

提交表单后,我们现在检查其是否有效。如果不是,那么我们将循环遍历所有FormControls(updateControls())并将状态更新为“ touched”(因为我们将在它们上设置错误,因此我们也可以将它们标记为“ touched”)。为了使Angular向其侦听器发送一个stateChange事件,我们需要使用updateValueAndValidity()。并且由于我们已经遍历了每个formControl,因此可以将onlySelf标志设置为true

属于以下形式的模板:

<form (ngSubmit)="submitForm()"
      [formGroup]="form"
      class="no-validate">

  <ng-content></ng-content>

</form>

通过确保Angular在表单无效时发出并发生事件,我们创建了一个可用于自定义消息的钩子(还记得Angular 1.x中的ng-messages吗?)。有关更多信息,请参见[此处] [2]。

如果要在模板中使用它,则外观如下:

<val-message-form (onSubmit)="login()" [formGroup]="form">
  <fieldset>
    <!-- Username -->
    <div class="form-group">
      <input type="email"
             formControlName="username">
    </div>

    <!-- Password -->
    <div class="form-group">
      <input type="password"
             formControlName="password">
    </div>

    <button type="submit" class="btn btn-success shadow-none">
      {{'LOGIN_PAGE.LOGIN.SHORT' | translate}}
    </button>
  </fieldset>
</val-message-form>

请注意[formGroup]标签,Angular使用相同的标签在表单上定义反应形式。从输入中删除标签会导致角度错误,告诉您它需要标签才能分配formControlName。我们可以通过使用相同的标记将表格注入指令中来确保程序员不会遇到此问题。 Angular会很高兴,您可以在指令内获取表格,实现双赢!

相关问题