0

I have some custom directive which i need to use in whole application. How to register my directives to use in whole application? Other questions I came across are all outdated. I need solution for angular 2 final version 2.1.0

my main.ts looks like this

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

//enableProdMode(); //Uncomment for production
platformBrowserDynamic().bootstrapModule(AppModule)
    .then((success: any) => console.log('App bootstrapped'))
    .catch((err: any) => console.error(err));

My app have 6 modules to use lazy oading

appmodule 
--contact module
--project module
--restmodules
...

When I registered the directive in product module, it worked well. So I used this directive in my rest of modules for which I registered this directive in appmodule.ts like this

import { mdinput} from './shared/mdinput.directive';


@NgModule({
    imports: [
               AppRoutingModule

    ],
    declarations: [
        AppComponent,mdinput

    ],
    providers: [DataService],
    bootstrap: [AppComponent]
})
export class AppModule {
}

now this particular directive is not working. Nor is it giving any errors.

3
  • Just add it to the declarations of your NgModule. angular.io/docs/ts/latest/guide/attribute-directives.html
    – JB Nizet
    Nov 23, 2016 at 7:44
  • @JBNizet but its not working diffrent modules Nov 23, 2016 at 7:46
  • Don't let us guess what you're trying to achieve. Edit your question, and post all the relevant information about your directive, your modules, etc. You probably need to add it to the exports, too, but without seeing anything, it's hard to guess.
    – JB Nizet
    Nov 23, 2016 at 7:48

2 Answers 2

5

First, create Directive in a separate directory. Let's say you created directive: myHighlight.directive.ts in customDirectives dir. Now

import { HighlightDirective } from 'yourpath/customDirectives/myHighlight.directive';

and

declarations: [..., HighlightDirective]

add these in app.module.ts.

Now use this in any component view:

<td  myHighlight>{{user.name | capitalize}}</td>

How this will work.

2

Just add it to a feature module and add the feature module to imports: [...] of the module where you want to use it.

Even *ngIf, *ngFor, ... now need to be added this way by adding CommonModule or BrowserModule to imports.

For more details see https://angular.io/docs/ts/latest/guide/ngmodule.html

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.