Difference between NG_VALIDATORS and validators (class)

I'm confused about what NG_VALIDATORS is using, I know it is a vendor token. But what is it to use? How is any class of form validators?

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

+3


source to share


1 answer


You have two ways to add validators to your form control. Using an imperative approach, specifying them as a parameter to control the form:

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

      

or declaratively, using special validator directives in the template:

<input [formControl]='ctrl' required>

      

The current is NG_VALIDATORS

used in the second case. These tokens are defined by validator directives required

, email

and others. And they are defined on the injector created by directives of the form - NgForm

, NgModel

and NgModelGroup

. See How exactly does the service hierarchy work in this Angular 2 app? to learn more about directives creating your own injector.

All built-in and custom validators are registered with 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 token NG_ASYNC_VALIDATORS

.

+3


source







All Articles