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

问题描述 投票:0回答:2

我有以下自定义验证器,它正常工作,没有任何问题。

@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中删除providers数组并将其放到app.module.ts时,如下所示,它无法正常工作。

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

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

angular angular-directive
2个回答
1
投票

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

NG_VALIDATORS令牌由Angular注入每个Form Control。当该指令在providers部分中指定某些内容时,它会将自身添加到该特定字段的注入令牌中。

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

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

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

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


0
投票

尝试:

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

export class AppModule { }

指令是在declarations而不是providers下宣布的

© www.soinside.com 2019 - 2024. All rights reserved.