angular – How to use NgModule modules and decorator?

Question:

I have doubts on how to use NgModule decorators. What are they and what are they for?

How to create a separate module to load one or more libraries and components?

For example, one to load Material Design dependencies and elements, one to load and start AngularFire, and one to load certain application components

Answer:

Modules are the main form of organization and architecture that angular provides. So anything related to architecture depends mainly on each project . But according to the official documentation, there are some general guidelines recommended as an architecture by features .

First let's see the existing fields in the modules:

Required:

imports -> Where you import other modules that your module depends on.

declarations -> Declarations of the components that are inside your module.

optional

exports -> Component declarations will be visible to other modules importing this module.

providers -> Service declarations from angular 6 you can declare the service to have a global scope within it leaving this option a little useless for newer applications.

You always have app.module which is the main module which loads other modules and their main routes. Anything loaded here will have a global scope in your application but will slow down when starting.

The point of having several modules is precisely to be able to have an extremely efficient application where each module only uses what it really needs. For example, not every module needs forms for example. This way and with the help of lazy loading, angular manages to make your application very light.

So let's see an example:

If you have a products feature that has, for example, a route/products that allows you to list and insert products, it makes sense to have a product module where you load these components (product-list, insert-product) and this module will only be loaded when your user enter /products which is quite useful for large applications.

Another interesting point are shared modules or shared modules that usually contain display-only components (they only contain inputs and outputs and no business logic). In this shared modules you can have, for example, a card module which in our example would have a product card and where this module is imported you will have access to that component. I recommend having several of these shared modules so you can have a botoes.module, cards.module or anything generic you can think of. Helping to share code and giving consistency to your project view.

Scroll to Top
AllEscort