如何为 FormGroup 触发 Angular 5 异步验证器 onblur

BSi*_*son 6 javascript onblur angular5

我采用了棱角分明的版本5.0.1,我试图触发一个AsyncValidatorFormGroup上的一个上一个模糊事件FormControlsFormGroup

我可以onBlur使用以下方法处理表单控件:

name: ['', {updateOn: 'blur'}]
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试将其应用于 a 时,FormGroup它不起作用。

是否可以只AsyncValidator onBlur在 a 上触发FormGroup,如果不能,只有在用户完成输入数据时才执行验证器的最佳方法是什么?

目前我唯一的其他选择是为我的验证器提供某种去抖动包装器。

只是通读这里,看来我应该能够updateOn: 'blur'用于表单组。

在 new FormGroup(value, {updateOn: 'blur'})) 之后;new FormControl(value, {updateOn: 'blur', asyncValidators: [myValidator]})

Vis*_*hnu 8

Angular5指定更新模式对于两种类型的表单都是可能的:template-driven formsreactive forms

第一个是为你工作。这是反应形式的工作示例

组件.ts

 import { Component, OnInit } from '@angular/core';
    import { FormGroup, FormControl, Validators } from '@angular/forms';
    @Component({
      selector: 'form01',
      templateUrl: './student.component.html',
      styleUrls: ['./student.component.scss']
    })
    export class StudentComponent implements OnInit {
    formTitle:string="Student registration ";
    nameForm: FormGroup;

    constructor() {
    }

    ngOnInit() {
      this.nameForm = new FormGroup ({
        firstname: new FormControl('', {
          validators: Validators.required,
          asyncValidators: [yourAsyncValidatorFunction],
          updateOn: 'blur'
        }),
        lastname: new FormControl('', {
          validators: Validators.required,
          asyncValidators: [yourAsyncValidatorFunction],
          updateOn: 'blur'
        })
      });
    }
    }
Run Code Online (Sandbox Code Playgroud)

HTML

<form [formGroup]="nameForm" novalidate>
  <div class="form-group">
    <label>What's your first name? </label>
    <input class="form-control" formControlName="firstname">
  </div>
  <div class="form-group">
    <label>What's your last name?</label>
    <input class="form-control" formControlName="lastname">
  </div>
  <button type="submit" class="btn btn-success">Submit</button>
</form>

  <h3>Hello {{nameForm.value.firstname}} {{nameForm.value.lastname}}</h3>
Run Code Online (Sandbox Code Playgroud)


Nie*_*eek 3

它在我这边起作用。请注意,FormBuilder 可能尚不支持此功能。

this.formGroup = new FormGroup({
  name: new FormControl('', {validators: []})
}, {
  updateOn: 'blur'
});
Run Code Online (Sandbox Code Playgroud)

  • Angular 7.1.0 及更高版本中的 FormBuilder 支持它 (3认同)