Search code examples
angulartypescriptangular-module

Angular2 - Importing angular modules


Modules are imported in app.module.ts, by adding an entry below,

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    DirectoryComponent,
    FilterPipe,
    LoggingService
  ],
  imports: [
    FormsModule,
    BrowserModule,
    HttpClientModule,
    routing
  ],
  providers: [],
  bootstrap: [AppComponent]
})

but RouterModule is directly used in ../src/app/app.routes.ts, as shown below,

import {Routes, RouterModule} from "@angular/router";
export const routes:Routes = [
    /* Each route will be an object {}*/
    {path: 'directory', component: DirectoryComponent},
    {path: '',          component: HomeComponent}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

There is no entry of RouterModule in @NgModule(imports: [..]).


1) Are there different ways to import an angular module?

2) Is import of angular module different from import of typescript module?


Solution

  • In your routes.ts you are creating the constant called routes, assigning it the RouterModule and exporting it.

    In your app, you're importing the routes constant, which is just a reference to the Module, just like any other:

    @NgModule(
     .... imports: [
             routing, // here you are using the const
          ],
    ....
    )
    

    And you are assigning it on this line:

     export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
    

    You could instead use the exported routes and use that in your app.module:

    @NgModule(
     .... imports: [
             RouterModule.forRoot(routes),
          ],
    ....
    

    The first is just assigning it to a variable (well const) before using it.

    Typescript modules are different from Angular modules. Typescript modules allow you to share typescript objects between typescript files. You use them everywhere, even in non angular typescript. They're the import { something } from 'myfile.ts' and it gets transpiled to JavaScript ES5 require statements, and just like ES6 importing. Not many people refer to these as modules much in my experience.

    Angular modules are modular chunks of angular components, services, directives and pipes etc bundled to so the compiler knows what to do with them, and you can easily compose angular apps from them. If anyone is talking about angular and modules it's likely they're talking about these because typescript modules are so fundamental - every typescript file will have multiple imports at the top.