本文介绍了在自定义验证器指令中注入 ngControl,导致循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建自定义的 angular 2 验证器指令,它像这样注入 NgControl:

i'm trying to create custom angular 2 validator directive, which inject NgControl like this :

@Directive({
  selector: '[ngModel][customValidator]',
  providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]
})
export class CustomValidatorDirective implements Validator {
  private validateFunction: ValidatorFn;

  constructor(private control: NgControl) { };

}

但我收到以下错误:

无法实例化循环依赖!控件

有谁知道我如何解决它,以便我可以在初始化后访问 ngControl?

Does anyone know how i can workarround it, so i can access the ngControl after intialization?

推荐答案

Providers, Pipes, Directives 声明已从 @Component 中删除或RC6RC7 之后的@Directive 装饰器.所以你只需要删除

Providers, Pipes, Directives declaration are removed from @Component or @Directive decorators after RC6 or RC7. So you just need to remove

providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]

来自指令

并将其添加到@NgModule({}) 装饰器

@NgModule({
 ...
 providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]

})

这篇关于在自定义验证器指令中注入 ngControl,导致循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:21