Import Directive into Component in Angular

Makla picture Makla · Nov 23, 2017 · Viewed 9.3k times · Source

Is it possible to import Directive into Component? I want to avoid importing into ngModule.declarations.

I am following CustomDirective for Telerik Angular Grid. It is suggested to populate grid with customDirective, but I will need this directive in only one component, so I want to avoid importing in ngModule, to avoid name collisions.

Edited:
I tried with viewProviders but it does not work. Here is plunkr that works (directive imported in ngModule):

@NgModule({
  imports: [ BrowserModule ],
  declarations: [
    AppComponent,
    HighlightDirective
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

and here is plunkr which doesn't work. (directive imported in Component):

@NgModule({
  imports: [ BrowserModule ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

@Component({
  moduleId: module.id,
  selector: 'my-app',
  templateUrl: 'app.component.html',
  viewProviders: [HighlightDirective]
})
export class AppComponent {
  color: string;
}

Answer

Armen Vardanyan picture Armen Vardanyan · Nov 23, 2017

Yes, this is entirely possible, you can use Component decorator's viewProviders option, like this:

@Component({
   template: '<div myCustomDirective>Hello</div>',
   selector: 'app-hello',
   viewProviders: [MyCustomDirective]
})
export class Component {}

But I should warn this is not really a best practice, trty to stick with the modules.