Import Directive into Component in Angular
Asked Answered
G

1

7

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;
}
Garland answered 23/11, 2017 at 8:27 Comment(3)
If you want to avoid name collisions then create dedicated @NgModule angular.io/guide/ngmodule#feature-modules There are conflicting directivesAhron
I also see no point in importing in NgModule if only one or two component will need it.Garland
@Fredrik Lundin wrote the right answer hereAhron
C
4

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.

Concrete answered 23/11, 2017 at 8:38 Comment(3)
viewProviders: [MyCustomDirective] This directive has nothing to do with template. It's provider not directive now. We have to declare directive in @NgModuleAhron
@Ahron I think I understand. Does that means it can't be done.Garland
@ArmenVardanyan Here works and here does not. Changes are in app.module.ts and app.component.ts.Garland

© 2022 - 2024 — McMap. All rights reserved.