-->

From within directive, how can I gain access to Ng

2019-03-03 23:22发布

问题:

I'm getting the error:

ERROR Error: StaticInjectorError(AppModule)[ControlDirective -> NgControl]: 
  StaticInjectorError(Platform: core)[ControlDirective -> NgControl]: 
    NullInjectorError: No provider for NgControl!
    at _NullInjector.get (core.js:1002)
    at resolveToken (core.js:1300)
    at tryResolveToken (core.js:1242)
    at StaticInjector.get (core.js:1110)
    at resolveToken (core.js:1300)
    at tryResolveToken (core.js:1242)
    at StaticInjector.get (core.js:1110)
    at resolveNgModuleDep (core.js:10854)
    at NgModuleRef_.get (core.js:12087)
    at resolveDep (core.js:12577)

When I try to inject NgControl in my component constructor like this:

  constructor(
    public renderer: Renderer2,
    public hostElement: ElementRef,
    private control: NgControl,
  ) {
    console.log(control);
  }

I tried adding it as a provider in my module, but looks like it's not an Injectable anymore.

What I'm trying to do is in the answer to this question. I'm seeing a number of older SO questions where NgControl is being injected, but looks like forms in Angular have changed quite a bit form earlier versions.

What I need to do is grab the control and add validators. What should I do differently to gain access to the control to do this?