Velidan Velidan - 1 year ago 101
TypeScript Question

Why sometimes we use NgModule and sometimes pure Components Angular 2

I have one question about Angular 2. I was working with it till RC4. Now I saw that major concepts was added (NgModule). I am trying to work with that but I don't understand why we use sometimes Module and sometimes only Component.

For example. Why we use Components instead Module? Why we didn't create NgModule wrapper for Crisis Center and navigate to it? I don't understand.

From official doc I uderstand that every logic unit should be different module that can be created via NgModule. Okay, no problem.

But after that I see that we just use pure components. I don't understand when I should use Module concept and when Component. I can't use module for routing?

But if I have many services/childComponents/pipes etc. in some component that I want to render on some path, so in that case should I create standard providers/directives decorators like in good old RC4?


import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

import { CrisisService } from './crisis.service';
import { CrisisDetailResolve } from './crisis-detail-resolve.service';

import { CrisisCenterComponent } from './crisis-center.component';
import { CrisisListComponent } from './crisis-list.component';
import { CrisisCenterHomeComponent } from './crisis-center-home.component';
import { CrisisDetailComponent } from './crisis-detail.component';

import { crisisCenterRouting } from './crisis-center.routing';

imports: [
declarations: [

providers: [
export class CrisisCenterModule {}

Answer Source

NgModule was introduced to support lazy loading in combination with the router. Therefore if you want to lazy load a part of your application only when the related route is actually being navigated to, then this part of your application has to go into it's own NgModule.

Besides that NgModule can be used to group together components, directives, pipes, and services according to your preference. Common is to create an NgModule for components, directives, pipes, and services that built together a "feature" that you might want to reuse at different places.

You can also put everything that is not lazy loaded into a single NgModule if you want, but it's not recommended.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download