How are these angular code snippets

So I was looking at the main angular files, I'm a little confused as to how these four pieces of code are connected?

  • Code for an input token which is a class
    export class InjectionToken extends OpaqueToken {
          private _differentiate_from_OpaqueToken_structurally: any;
          constructor (desc: string) {super (desc); }

          toString (): string {return `InjectionToken $ {this._desc}`; }
    }

  1. Code for NG_VALIDATORS which uses the input token
    export const NG_VALIDATORS = new InjectionToken> ('NgValidators');

  1. Mandatory validator that uses NG_VALIDATORS
    export const REQUIRED_VALIDATOR: Provider = {   
        provide: NG_VALIDATORS,   
        useExisting: forwardRef (() => RequiredValidator),   
        multi: true 
    };

    @Directive ({
        ...
    }) export class RequiredValidator implements Validator {
        // Code here
    }

I'm having a problem tracking code from a REQUIRED_VALIDATOR declaration for an input token. I understand most of the basic elements, but I don't know how "useExisting" is used for the RequiredValidator class (I understand forwardRef). And how does NG_VALIDATORS win, which itself is a constant by definition

+1


source to share


1 answer


In the Angular DI system, a token can be any reference available at runtime , including a class instance. So here you have an instance of the class InjectionToken

:

export const NG_VALIDATORS = new InjectionToken>('NgValidators');

      

which the variable refers to NG_VALIDATORS

.

Angular DI System introduces a strategy that can redirect a request from one token to another. And this strategy is used here:

export const REQUIRED_VALIDATOR: Provider = {   
    provide: NG_VALIDATORS,   
    useExisting: forwardRef(() => RequiredValidator),   
    multi: true 
};

      

But what is it redirecting to? It redirects to the token referenced by the class RequiredValidator

. To understand where it comes from RequiredValidator

, you need to know that Angular adds instances of the directive class to the element injector. Therefore, if you have two directives:

@Directive({selector:'adir'...}) export class ADirective {}
@Directive({selector:'bdir'...}) export class BDirective {}

      

And apply them like this:



<input adir bdir>

      

An injector created on these elements will contain the following suppliers:

[
  { token: ADirective, instance: new ADirective() },
  { token: BDirective, instance: new BDirective() }
]

      

And so any directive added to this element will be able to insert these instances by the class marker.

So, in the case of the required

validator, when you apply the directive required

to the element:

<input required>

      

in the injector, the instance RequiredValidator

is created by the token RequiredValidator

, and that's exactly the token to be redirected to NG_VALIDATORS

.

+1


source







All Articles