Angular自定义异步表单验证

1.自定义一个异步的表单验证器

<form [formGroup]="userForm">
<input type="text" formControlName = "name">
<button (click)="form.reset()">Reset</button>
</form>

//第一个参数是初始值, 第二个参数是同步验证器,第三个是异步验证器
const nameControl = new FormControl(' ', [Validators.required], [this.nameAsyncValidator] );
this.userForm = new FormGroup([
name:nameControl
])
//异步验证方法
nameAsyncValidator = (control: AbstractControl ): Observable<{ nameAsync: boolean} | null> =>{
if (control.value === 'admin'){
  return of({nameAsync: true})
}else{
  return of(null);
}
} 

2.提醒:使用form的reset()方法的时候,会把表单里的每一项值都放为空,而表单中input表单的初始值是‘ ’,所以调用reset方法会有问题。需要给FormControl里面加参数(noNullable: true)。

<form [formGroup]="userForm">
<input type="text" formControlName = "name">
<button (click)="form.reset()">Reset</button>
</form>
//改前:
const nameControl = new FormControl(' ', [Validators.required], 
this.nameAsyncValidator );
//改后:
const nameControl = new FormControl(' ', 
{nonNullable: true,
validators: [Validators.required], 
asyncValidators: [this.nameAsyncValidator]} );

this.userForm = new FormGroup([
name: nameControl
])

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-21 19:22:06       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-21 19:22:06       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-21 19:22:06       82 阅读
  4. Python语言-面向对象

    2024-04-21 19:22:06       91 阅读

热门阅读

  1. Scala之面向对象 Day -3

    2024-04-21 19:22:06       44 阅读
  2. 134. 加油站

    2024-04-21 19:22:06       30 阅读
  3. 【设计模式】享元模式

    2024-04-21 19:22:06       40 阅读
  4. 批量控制教程-Ansible管理windows

    2024-04-21 19:22:06       41 阅读
  5. 【Ansible】02

    2024-04-21 19:22:06       35 阅读
  6. linux的工具tcptrace的输出信息的解释和介绍

    2024-04-21 19:22:06       38 阅读
  7. 【设计模式】7、decorate 装饰模式

    2024-04-21 19:22:06       34 阅读
  8. 黑马点评项目遇到的部分问题

    2024-04-21 19:22:06       124 阅读
  9. 关于指针变量的理解

    2024-04-21 19:22:06       39 阅读
  10. react脚手架创建项目,配置别名(alias)

    2024-04-21 19:22:06       39 阅读