Angular 2 Modules

This week I decided to look into Routing With Modules. By using the new @NgModule decorator we’re able to define modules in our Angular 2 application. The decorator is attached to a class an contains a set of meta data which describes the module. According to the official Angular 2 documentation Angular 2 modules are used to “help organize an application into cohesive blocks of functionality”.

Advantages of modularity in Angular 2

  • Application can be organized in smaller blocks of functionality
  • Easy to extend application by including modules (e.g. for external libraries)
  • Angular 2 offers standard libraries like: FormsModule, HttpModule, RouterModule
  • Angular Modules consolidate components, directives and pipes into blocks of functionality

In fact, Angular 2 modules can be used for different purposes:

One application module is defined for each application. This module is named AppModule and implemented in file app.module.ts by convention. The application / root module is the main entry point and contains components, pipes and services which do not belong the subsequent feature modules and should be available application-wide.

In addition to the application module, feature modules can help to further structure your application and group your implementation in blocks of functionality. Furthermore feature modules can speed up your application and enable lazy-loading. When your app starts you may not want that everything is loaded at once. Feature areas which are not needed first can be loaded later. Keeping everything together in a feature module is the prerequesite for enabling lazy-loading in your app.

Modules are also used to encapsulate router configuration. Configuring routes can be done on the level application level (for AppModule) or on the level of subsequent feature modules. By specify routes we’re defining which component should be loaded and displayed when the user points to a certain URL in the browser.

Source: https://medium.com/codingthesmartway-com-blog/angular-2-routing-with-modules-dd9e25bdd651

Leave a comment