简体   繁体   English

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

[英]How to fire Angular 5 async validator onblur for FormGroup

I am using Angular version 5.0.1 and I'm trying to fire an AsyncValidator on a FormGroup on a blur event on one of the FormControls in the FormGroup .我采用了棱角分明的版本5.0.1,我试图触发一个AsyncValidatorFormGroup上的一个上一个模糊事件FormControlsFormGroup

I can get onBlur to work on a form control using the following:我可以使用以下方法让onBlur处理表单控件:

name: ['', {updateOn: 'blur'}]

However, when I try to apply it to a FormGroup it doesn't work.但是,当我尝试将其应用于FormGroup它不起作用。

Is it possible to only fire an AsyncValidator onBlur on a FormGroup , and if not, what is the best way to execute the validator only when the user has finished entering data?是否有可能只是触发一个AsyncValidator onBlurFormGroup ,如果没有,什么是执行,只有当用户完成数据输入验证的最好方法?

My only other option at the moment is to us some sort of debounce wrapper for my validator.目前我唯一的其他选择是为我们的验证器提供某种去抖动包装器。

Just reading through here and it appears I should be able to use updateOn: 'blur' for a form group.只是通读这里,似乎我应该能够使用updateOn: 'blur'作为表单组。

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

In Angular5 Specifying the update mode is possible for both types of forms: template-driven forms and reactive forms .Angular5 ,可以为两种类型的表单指定更新模式: template-driven formsreactive forms

First one is working for you.第一个是为你工作。 Here's the working example for reactive forms这是反应形式的工作示例

Component.ts组件.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'
        })
      });
    }
    }

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

It works on my side.它在我身边工作。 Be aware that the FormBuilder may not support this yet.请注意,FormBuilder 可能尚不支持此功能。

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

I use this code snippet combining AbstractControlOptions with FormBuilder :我使用这个代码片段结合AbstractControlOptionsFormBuilder

 constructor(private formBuilder: FormBuilder) { }
 
 this.signUpForm = new FormGroup(
   this.formBuilder.group({
     'email':    ['', ValidationUtils.emailValidators()],
     'fullname': ['', ValidationUtils.fullnameValidators()],
     'idCard':   ['', ValidationUtils.idCardValidators()],
     'username': {value: '', disabled: true}
   }).controls, {
     updateOn: 'blur'
   }
 );

you can add this directive你可以添加这个指令

import { Directive,Output, HostListener, EventEmitter } from '@angular/core';

@Directive({
  selector: '[onBlur]'
})
export class OnBlurDirective {
  // @Input('onBlur') onBlurFunction: Function;
  @Output('onBlur') onBlurEvent: EventEmitter<any> = new EventEmitter();
  constructor() { }
  @HostListener('focusout', ['$event.target'])
  onFocusout(target) {
    console.log("Focus out called");
    this.onBlurEvent.emit()
  }
}

and use it in the HTML like this并像这样在 HTML 中使用它

<input type="text" (onBlur)="myFunction()"/>

and in the component you can define the function myFunction as you want在组件中,您可以根据需要定义函数myFunction

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM