在Angular中,我们可以使用Reactive Forms来创建动态表单,并为其提供自定义验证。然而,有时在第一次更改验证以后,验证器可能不会更新。这可能是因为表单控件的值仍然保持不变的缘故。
要解决这个问题,我们需要使用值更改的Observable,并手动调用验证函数。以下是一个解决方案的代码示例:
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-custom-validation',
template: `
`,
})
export class CustomValidationComponent {
form = new FormGroup({
password: new FormControl('', [
Validators.required,
Validators.minLength(8),
Validators.pattern(/\d/),
]),
});
constructor() {
// subscribe to value changes and manually call validation function
this.form.get('password').valueChanges.subscribe(() => {
this.form.get('password').updateValueAndValidity();
});
}
}
在代码中,我们订阅了密码控件的值更改Observable,并在每次更改时手动调用了控件的updateValueAndValidity
方法。这将强制表单重新计算验证器并更新表单状态。现在,第一次更改验证器后,表单将更新状态并按预期工作。