Search code examples
javascriptangularangular2-modules

Angular 2 Module Imports


I have my main module like this, where I import the basic Libraries :

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { MapModule } from './map/map.module';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MapModule,
    MaterialModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

My question is when I create a new Module within the app i.e Map Module do I need to reimport all those libraries to that Module. I was under the impression that if I import the libraries on the module it would work under child modules.

But in my Map Module I am getting errors like.

Can't bind to 'ngClass' since it isn't a known property of 'div'.

My Current MapModule looks like

import { NgModule } from '@angular/core';

import { MapComponent } from './map.component';
import { MapMenuComponent } from './map-menu/map-menu.component';
import { MapControlsComponent } from './map-controls/map-controls.component';
import { MapService } from './map.service';


@NgModule({
    imports: [],
    exports: [],
    declarations: [MapMenuComponent, MapControlsComponent, MapComponent],
    providers: [MapService],
})
export class MapModule { }

Do I need to reimport the MaterialModule, Forms etc into module again for the components in this module to work ?


Solution

  • You only need to reimport modules with declarations, i.e. modules that define new components, directives and pipes. Modules that register providers don't need to be imported.

    In this list:

      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        MapModule,
        MaterialModule.forRoot()
      ],
    

    FormsModule modules need to be imported, by HttpModule need not. BrowserModule re-exports CommonModule, so in the other modules you would probably want to import CommonModule, not BrowserModule to get built-in directives like NgClass. By importing CommonModule you will not have this error:

    Can't bind to 'ngClass' since it isn't a known property of 'div'.