繁体   English   中英

如何在 angular 反应式表单构建器中调用异步验证器 function 模糊?

[英]How call async validator function on blur in angular reactive form builder?

我的异步验证 function 调用每个keyup事件。 如何在blue事件上调用异步 function。 注册组件代码::

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { UserService } from '../../services/user.service';
import { ApiError } from '../../models/apierror';
import { UniqueUsername } from '../class/unique-username';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css'],
})
export class RegisterComponent implements OnInit {
  error!: ApiError;
  submitted = false;

  registrationForm!: FormGroup;

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private userService: UserService,
    private uniqueUsername: UniqueUsername
  ) {}

  ngOnInit(): void {
    this.registrationForm = this.fb.group({
      name: ['', Validators.required],
      username: [
        '',
        [Validators.required],
        [this.uniqueUsername.validate.bind(this.uniqueUsername)],
      ],
      password: ['', Validators.required],
    });
  }

  get name() {
    return this.registrationForm.get('name');
  }

  get username() {
    return this.registrationForm.get('username');
  }

  get password() {
    return this.registrationForm.get('password');
  }

  onSubmit() {
    const formData = new FormData();
    formData.append('name', this.registrationForm.get('name')!.value);
    formData.append('username', this.registrationForm.get('username')!.value);
    formData.append('password', this.registrationForm.get('password')!.value);
  }

  gotoHome() {
    this.router.navigate(['/']);
  }
}

异步验证器 class 代码::

import { Injectable } from '@angular/core';
import {
  AbstractControl,
  AsyncValidator,
  ValidationErrors,
} from '@angular/forms';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import { UserService } from '../../services/user.service';

@Injectable({ providedIn: 'root' })
export class UniqueUsername implements AsyncValidator {
  constructor(private userService: UserService) {}

  validate(control: AbstractControl): Observable<ValidationErrors | null> {
    const { value } = control;
    return this.userService.checkUsername(value).pipe(
      map((isExist: boolean) => (isExist ? { uniqueUserName: true } : null)),
      catchError(() => of(null))
    );
  }
}

将 AbstractControlOptions 与 FormBuilder 结合:

 this.registrationForm = new FormGroup(
   this.fb.group({
     name: ['', Validators.required],
      username: [
        '',
        [Validators.required],
        [this.uniqueUsername.validate.bind(this.uniqueUsername)],
      ],
      password: ['', Validators.required],
   }).controls, {
     updateOn: 'blur'
   }
 );

您可以使用AbstractControlOptions界面中updateOn:'blur' 其他可用选项是changesubmit

使用 FormGroup 和 FormControl 的构造函数

  form=new FormGroup({
    ...
    username:new FormControl('',{
                              validators:Validators.required,
                              asyncValidators:this.uniqueUsername.validate.bind(this.uniqueUsername),
                              updateOn:'blur'
                             }
   )
  })

使用表单生成器

   form=this.fb.group({
      ...
      username:this.fb.control('',{
                        validators:Validators.required,
                        asyncValidators:this.uniqueUsername.validate.bind(this.uniqueUsername),
                        updateOn:'blur',
                              })
   })

//or

   form=this.fb.group({
      ...
      username:['',{
                    validators:Validators.required,
                    asyncValidators:this.uniqueUsername.validate.bind(this.uniqueUsername),
                    updateOn:'blur',
                              }]
   })

暂无
暂无

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

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