dmd
dmd

Reputation: 387

NgControl in Directive: No Provider for NgControl

I have a Directive which I would like to inject 'NgControl' but got 'No provider for NgControl' error.

My File Directory is as following:

app folder
 |--directives folder
        |--myDirective
 |
 |--components folder
        |--events folder
             |--event.module.ts
             |--event1 folder          
                 |--event1.compoenent.html <-- where I use myDirective, which is a reactive form
                 |--event1.component.ts
        
 |--app.module.ts
 |--custom-material.module.ts <-- where I declare my myDirective

my directive:

import { Directive, OnInit, OnDestroy } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: "[myDirective]"
})
export class myDirective implements OnInit{

  constructor(public ngControl: NgControl) {}

   ngOnInit(): void {
    this.ngControl.control.valueChanges.subscribe(
      value => {
          console.log('xxx');
      }
    );
  }

}

my custom-material.module.ts

@NgModule({
  imports:      [ FormsModule, ReactiveFormsModule ],
  declarations: [ myDirective ],
  exports: [
    myDirective
  ],
})
export class CustomMaterialModule { 

}

Upvotes: 0

Views: 2769

Answers (1)

Mackelito
Mackelito

Reputation: 4421

Try this constructor in your directive..

  constructor(@Optional() @Self() public ngControl: NgControl) {}

Upvotes: 2

Related Questions