Search code examples
typescriptangular7angular8

How to use common directive for lazy load modules in angular 8


I have created one directive for numbers only type.I have imported that in root app module but i am not able to use in lazy modules.How to resolve this issue?

Demo: https://stackblitz.com/edit/angular-pctddo-1pyfzu?file=src%2Fapp%2Fapp.module.ts

app.module.ts:

import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NumberDirective } from './numbers-only.directive';
@NgModule({
  declarations: [
    AppComponent,
    NumberDirective
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
 })
 export class AppModule { }

customer-list.component.html

<input type="text" numbersOnly placeholder="Numbers only">

order-list.component.html

<input type="text" numbersOnly placeholder="Numbers only">

app-routing.module.ts:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';


const routes: Routes = [
  {
    path: 'customers',
    loadChildren: './customers/customers.module#CustomersModule'
  },
  {
    path: 'orders',
    loadChildren: './orders/orders.module#OrdersModule'
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule],
  providers: []
})
export class AppRoutingModule { }

Solution

  • You can create an ui-module for it. By this way, you can import DirectivesModule which module you want to use it.

    Another way is that you can use AppModule or SharedModule if your directives are very common.

    I updated your Stackblitz.

    directives.module.ts

    @NgModule({
      imports: [CommonModule],
      declarations: [NumberDirective],
      exports: [NumberDirective]
    })
    
    export class DirectivesModule {}
    

    Why you need to export your directives from DirectivesModule?

    If you don't export your directives, your application registers directives only and only inside your DirectivesModule

    Lastly, you need to import it at your lazy module.

    lazy.module.ts

    @NgModule({
      imports: [
        DirectivesModule
      ],
      declarations: [...]
    })
    export class LazyModule { }