docs: expand async validators in reactive forms (#44764)

* Hone docregions for code examples
* Add more detailed description

PR Close #44764
This commit is contained in:
Tim Bowersox
2022-01-21 19:17:41 -05:00
committed by Andrew Kushnir
parent 2c40b7d250
commit 4948ab9ee5
2 changed files with 20 additions and 9 deletions
@@ -19,18 +19,21 @@ export class HeroFormReactiveComponent implements OnInit {
heroForm: FormGroup;
ngOnInit(): void {
// #docregion async-validator-usage
const alterEgoControl = new FormControl('', {
asyncValidators: [this.alterEgoValidator.validate.bind(this.alterEgoValidator)],
updateOn: 'blur'
});
alterEgoControl.setValue(this.hero.alterEgo);
// #enddocregion async-validator-usage
this.heroForm = new FormGroup({
name: new FormControl(this.hero.name, [
Validators.required,
Validators.minLength(4),
forbiddenNameValidator(/bob/i)
]),
// #docregion async-validator
alterEgo: new FormControl(this.hero.alterEgo, {
asyncValidators: [this.alterEgoValidator.validate.bind(this.alterEgoValidator)],
updateOn: 'blur'
}),
// #enddocregion async-validator
alterEgo: alterEgoControl,
power: new FormControl(this.hero.power, Validators.required)
});
}
@@ -40,6 +43,8 @@ export class HeroFormReactiveComponent implements OnInit {
get power() { return this.heroForm.get('power'); }
get alterEgo() { return this.heroForm.get('alterEgo'); }
// #docregion async-validator-inject
constructor(private alterEgoValidator: UniqueAlterEgoValidator) {}
// #enddocregion async-validator-inject
}
+8 -2
View File
@@ -335,9 +335,15 @@ The `pending` flag is set to `false`, and the form validity is updated.
### Adding async validators to reactive forms
In reactive forms, add an async validator by passing the function directly to the `FormControl`.
To use an async validator in reactive forms, begin by injecting the validator into the constructor of the component class.
<code-example path="form-validation/src/app/reactive/hero-form-reactive.component.2.ts" region="async-validator"></code-example>
<code-example path="form-validation/src/app/reactive/hero-form-reactive.component.2.ts" region="async-validator-inject"></code-example>
Then, pass the validator function directly to the `FormControl` to apply it.
In the following example, the `validate` function of `UniqueAlterEgoValidator` is applied to `alterEgoControl` by passing it to the control's `asyncValidators` option and binding it to the instance of `UniqueAlterEgoValidator` that was injected into `HeroFormReactiveComponent`. The value of `asyncValidators` can be either a single async validator function, or an array of functions.
<code-example path="form-validation/src/app/reactive/hero-form-reactive.component.2.ts" region="async-validator-usage"></code-example>
### Adding async validators to template-driven forms