app.module 中提供的自定义指令不起作用

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

我有以下自定义验证器,它按预期工作没有问题。

@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;
    }   
}

当我从 TestValudatorDirective 中删除提供程序数组并将其放入下面的 app.module.ts 时,它不起作用。

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

任何人都可以向我解释这种行为,我有点困惑。

尝试:

.....
declaration : [
   TestValidatorDirective , < -- add here
   //... other components
 ],
bootstrap: [AppComponent]
})

export class AppModule { }

指令是在 declarations 而不是 providers

下声明的

无需将您的验证器移至 AppModule。为了能够在任何你想要的地方使用你的验证器,你只需要确保它在你的模块的 declarations 中。

NG_VALIDATORS 标记由 Angular 注入到每个表单控件中。当此指令在 providers 部分指定某些内容时,它会将自身添加到 that 特定字段的注入标记中。

所以这不像是向 providers 部分添加服务......在这种情况下它不应该在模块中。

但是您的模块应该允许使用指令,因此需要将指令添加到声明中:

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

有一篇很好的 Thoughtram 文章很好地涵盖了这个主题:https://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html