-1

I went into few videos explaining NgModules and the official Angular documentation about NgModules but I'm still having a grasp about how it works.

I understand that components goes into declarations, modules into imports and services into providers (I also heard that since Angular v6, services don't need to be declare at all?). What I don't understand is when and why to create "sub NgModules" like auth.module.ts.

  • Why should I create those sub NgModules?
  • What is the benefit vs using only app.modules.ts?
  • Should I import those sub NgModules into app.modules.ts?
  • Is there any other things I need to know about NgModules?

Thanks

KevinTale
  • 1,658
  • 3
  • 25
  • 47

2 Answers2

2

Why should I create those sub NgModules?

Angular follows a modular structure to enhance code structuring, readability and re-usability. Quoting the docs:

NgModules consolidate components, directives, and pipes into cohesive blocks of functionality, each focused on a feature area, application business domain, workflow, or common collection of utilities.

Additionally, sub-modules allow you to implement lazy loading.

What is the benefit vs using only app.modules.ts?

Angular recommends a Modular structure for reasons mentioned above. Additionally, check out the style guide.

Should I import those sub NgModules into app.modules.ts?

It depends. If you use routing, you can lazy-load these modules and as such don't have to import them into the root module. Angular will do that itself, once a URL associated with this module is hit. You will have to configure this behavior, of course.

Is there any other things I need to know about NgModules?

There is a LOT of useful documentation on ngModules over at the official docs. In fact, most, if not all of your questions can be answered by reading them in depth.

NgModule FAQs: https://angular.io/guide/ngmodule-faq

Aamir Khan
  • 2,945
  • 2
  • 25
  • 32
1

First of all, I strongly recommend you that go through the Angular official site for the better understanding. I can explain you in one word.

1) Why should I create those sub NgModules?

You can implement Lazy-loading.

2)What is the benefit vs using only app.modules.ts?

You can register each thing you create in Angular, and group them together.

3)Should I import those sub NgModules into app.modules.ts?

Yes, You have to do that. But, if you are implementing lazy-loading it is not necessary to do so.

4)Is there any other things I need to know about NgModules?

Yes, Refer this link or go through the Angular official documentation.

Arun Raj R
  • 2,197
  • 3
  • 13
  • 23