在异步验证器外围使用setTimeout函数包装并添加async/await语法来解决这个问题。以下是示例代码:
import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-example',
template: `
`
})
export class ExampleComponent implements OnInit {
form: FormGroup;
ngOnInit() {
this.form = new FormGroup({
test: new FormControl(null, [Validators.required], [this.customValidatorAsync.bind(this)])
});
}
async customValidatorAsync(control: FormControl) {
await new Promise(resolve => setTimeout(resolve, 1000));
if (control.value === 'invalid') {
return { customError: true };
}
return null;
}
async submit() {
if (this.form.valid) {
console.log('Valid Submitted', this.form.value);
} else {
console.log('Invalid Form', this.form);
}
}
}