要解决Angular自定义异步验证器不显示错误的问题,你可以按照以下步骤进行操作:
import { AbstractControl, ValidationErrors } from '@angular/forms';
import { Observable } from 'rxjs';
export function customAsyncValidator(control: AbstractControl): Promise | Observable {
return new Promise((resolve, reject) => {
// 异步验证逻辑
// 如果验证通过,则调用resolve(null)
// 如果验证失败,则调用resolve({ customError: true })
});
}
async
管道来显示错误信息。
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { customAsyncValidator } from './custom-async-validator';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
myInput: ['', Validators.required, customAsyncValidator]
});
}
}
通过以上步骤,你应该能够解决Angular自定义异步验证器不显示错误的问题,并在表单控件上正确显示错误消息。