Velidan Velidan - 1 month ago 9
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?

Thanks.

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';

@NgModule({
imports: [
CommonModule,
FormsModule,
crisisCenterRouting
],
declarations: [
CrisisCenterComponent,
CrisisListComponent,
CrisisCenterHomeComponent,
CrisisDetailComponent
],

providers: [
CrisisService,
CrisisDetailResolve
]
})
export class CrisisCenterModule {}

Answer

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.

Comments