Import Directive into Component in Angular

Import Directive into Component in Angular

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;
}
3

1 Answer

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.

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.