Intro to Angular Modules

Angular Modules picture

Angular (not to be confused with AngularJS) is a very large and powerful tool for creating applications. Some of the topics and uses of Angular are more difficult to understand than others. In this blog I’ll be covering Modules, something that I still don’t fully grasp. If you’re like me, then read on to try and understand what they are and how to use them.

Angular apps are made up of different modules. Those modules are then made up of different components, service providers and other related files. Modules can share, or import and export functionality from other NgModules. At the heart of every Angular application is the root module (AppModule in the example above).

declarations: [*]
Declarations are the components, directives, and pipes that belong to an NgModule.1

So, what does that actually mean? If an angular app is made up of different modules, then think about the different modules being made up of different components. The declarations of a module are what that module are dependent upon to work properly/what the module is made up of.

exports: [*]
Exports are the components of the current module that you want to expose, or make available, to other modules in the application. Think of it as making a component, directive or pipe publicly accessible to any other component that may need to consume it.

imports: [*]
Imports then, logically, refer to components from other modules that you’d like the current module to consume. If you export a module you can then import it somewhere else.

providers: [*]
A provider is something that the Dependency Injection system instructs your application on how to obtain.2 This generally relates to a service that you’ve created within your app. Providers are Injectable services to be used throughout your application. How you specify the accessibility of your service will dictate where it can be used. If you specify a provider at the root level, it will be available to your entire application.

According to the provider documentation you should always specify a provider at the root level unless you want the service to be available only if the consumer imports a particular @NgModule.

bootstrap: [*]
The bootstrap array should only be listed at the app root level. Meaning mainly in app.module.ts. This is what launches the application and adds the components to the browser DOM. This generally doesn’t need to be changed, unless you want a different module to be the entry point for your application.

After writing this I still know there are an infinite list of things I need to learn about NgModule’s. This list should help give a basic understanding of what each part does.


1 https://angular.io/guide/architecture-modules
2 https://angular.io/guide/providers#providers

Leave a Reply

Your email address will not be published. Required fields are marked *