Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between NG_VALIDATORS and validators (Class)

Tags:

angular

I'm confused on what's the usage of NG_VALIDATORS, I know it is a provider token. But what's its use? How is it any different form validators class?

https://github.com/angular/angular/blob/4.3.3/packages/forms/src/validators.ts

like image 892
Jdsans Avatar asked Dec 11 '22 10:12

Jdsans


1 Answers

You have two ways to add validators to a form control. Using imperative approach by specifying them as a parameter to a form control:

const ctrl = new FormControl('', Validators.required);

or declaratively by using validator specific directives in the template:

<input [formControl]='ctrl' required>

The NG_VALIDATORS token is used in the second case. These tokens are defined by the validators directives required, email an others. And they are defined on the injector created by form directives - NgForm, NgModel and NgModelGroup. See How exactly works the services hierarchy in this Angular 2 application? to learn more about directives creating its own injector.

All built-in and custom validators are registered using this token:

export const EMAIL_VALIDATOR: any = {
  provide: NG_VALIDATORS,
  useExisting: forwardRef(() => EmailValidator),
  multi: true
};
@Directive({
  selector: '[email]...',
  providers: [EMAIL_VALIDATOR]  <-------------
})
export class EmailValidator implements Validator {

export const REQUIRED_VALIDATOR: Provider = {
  provide: NG_VALIDATORS,
  useExisting: forwardRef(() => RequiredValidator),
  multi: true
};
@Directive({
  selector:
      '[required]...',
  providers: [REQUIRED_VALIDATOR],  <-------------
})
export class RequiredValidator implements Validator {

Angular reactive and template driven form directives (NgForm, NgModel and NgModelGroup) inject validators using this token:

export class NgForm extends ControlContainer implements Form {
  ...    
  constructor(
      @Optional() @Self() @Inject(NG_VALIDATORS) validators: any[],

export class NgModel extends NgControl implements OnChanges,
  ...
  constructor(@Optional() @Self() @Inject(NG_VALIDATORS) validators...,

export class NgModelGroup extends AbstractFormGroupDirective implements ... {
  ...
  constructor(
      @Optional() @Self() @Inject(NG_VALIDATORS) validators: any[],

The same goes for the NG_ASYNC_VALIDATORS token.

like image 181
Max Koretskyi Avatar answered Feb 04 '23 21:02

Max Koretskyi