Search code examples
angularangular-directive

Custom directive not working when it is provided in app.module


I have the following custom validator which is working as expected with no problems.

@Directive({
    selector:'[TestValidator]',
    providers:[
        { provide: NG_VALIDATORS, useExisting:TestValidatorDirective, multi:true}
    ]
})
export class TestValidatorDirective implements Validator{

    validate(control:AbstractControl):ValidationErrors|null {
       return  control.value == '-1' ? {'defaultSelected':true} : null;
    }   
}

When i remove the providers array from TestValudatorDirective and put it to the app.module.ts like below it is not working.

.....
providers: [
      { provide: NG_VALIDATORS, useExisting:TestValidatorDirective, multi:true}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Can anyone explain this behaviour to me, i am kind of confused.


Solution

  • There is no need to move your validator to the AppModule. To be able to use your validator wherever you want it, you just need to ensure it is in the declarations of your module.

    The NG_VALIDATORS token is injected into each Form Control by Angular. When this directive specifies something in the providers section, it's adding itself to that injection token for that particular field.

    So it's not like adding a service to the providers section ... it shouldn't be in the module in this case.

    But your module should allow the directive to be used, so needs to add the directive to the declarations:

    @NgModule({
      //...
      delcarations: [
        TestValidatorDirective
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    There's a good Thoughtram article which covers this topic really well: https://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html