Search code examples
angulartypescriptangular-directiveangular-module

Custom directive is not working inside angular module?


In my app, i have two modules. IdentityModule and ServiceModule. They are loaded as lazyloading technology.

Now I have created a custom directive IconSpacerDirective that is bind with app.module.ts. It's working fine inside my app.component.ts.

But it's not working inside the IdentityModule. I am having this error:

ERROR Error: Uncaught (in promise): Error: Type IconSpacerDirective is part of the declarations of 2 modules: AppModule and IdentityRegistryModule! Please consider moving IconSpacerDirective to a higher module that imports AppModule and IdentityRegistryModule. You can also create a new NgModule that exports and includes IconSpacerDirective then import that NgModule in AppModule and IdentityRegistryModule.
Error: Type IconSpacerDirective is part of the declarations of 2 modules: AppModule and IdentityRegistryModule! Please consider moving IconSpacerDirective to a higher module that imports AppModule and IdentityRegistryModule. You can also create a new NgModule that exports and includes IconSpacerDirective then import that NgModule in AppModule and IdentityRegistryModule.

Here is my identityRegistryModule:

import { IconSpacerDirective } from '../shared/custom-directive/icon-spacer.directive';
@NgModule({
  declarations: [
    IconSpacerDirective
  ],
  imports: [
    IdentityRegistryRoutingModule,
    MaterialModule   

  ],
  providers: [
    IdentityService,
  ],
})
export class IdentityRegistryModule { }

my app.module.ts as follows:

import { IconSpacerDirective } from './shared/custom-directive/icon-spacer.directive';

@NgModule({
  declarations: [
    AppComponent,
    MainNavComponent,
    SideNavComponent,
    HeaderComponent,
    HomeComponent,
    IconSpacerDirective,

  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule,
    FlexLayoutModule,
    BrowserAnimationsModule,
    LayoutModule,
    MaterialModule,
    OAuthModule.forRoot(),
  ],
  providers: [],
  bootstrap: [AppComponent],
  //exports: [IconSpacerDirective]
})
export class AppModule { }

How can i use the IconSpacerDirective inside my identityRegistryModule


Solution

  • If you want to use the IconSpacerDirective in both the AppModule and the IdentityRegistryModule, then you need to create a separate module for that directive that you can then import in the modules where you need it.

    @NgModule({
      declarations: [IconSpacerDirective],
      exports: [IconSpacerDirective]
    })
    export class IconSpacerModule { }
    
    @NgModule({
      imports: [IconSpacerModule]
    })
    export class AppModule { }
    
    @NgModule({
      imports: [IconSpacerModule]
    })
    export class IdentityRegistryModule { }