Structure Module In Angular
- What is Module?
Module in Angular refers to a place where you can group the components, directives, pipes, and services, which are related to the application. In case you are developing a website, the header, footer, left, center and the right section become part of a module. To define module, we can use the NgModule.
2. App Module
Everything in Angular is organized in modules. Even if you don’t know, when you create a new project via CLI, angular-cli creates the “App.module” class for you. This module is the root module of the application and is absolutely necessary for it to run. This class specifies which components and modules will be used in the application.
3. A Basic Use of Modules
3.1 @NgModule
Angular Module is actually a javascript class and to define it, the @NgModule operator must be used so that Angular can recognize this class as a module.
3.1.1 Bootstrap
To bootstrap our module based application, we need to inform Angular which one is our root module to perform the compilation in the browser.
The root component of the application is defined here. We only use this property inside App Module.
3.1.2 Exports
We define the components, directives, pipes we want to use. In this way, we can access these components from anywhere we want to use the module. Otherwise, these components remain inside the module and cannot be accessed from the outside.
3.1.3 Declarations
Within the Declarations array, we define all the components, directives and pipes declared and used within this module. When you want to use it within the application without adding components, directives or pipes to this array, you will get an error in the runtime by Angular. Also, a component can only be declared in a module. To use that component in more than one module, you need to import the module you define the component in the modules you want to use.
3.1.4 Imports
You can add as many submodules as you want to the module. These modules can be angular modules as well as modules that you write custom. Angular is built on a modular structure.
Angular already includes many features.
For example;
For the Http Clients that you will use in your projects, it will be sufficient to import the Http Client Module.
3.1.5 Providers
A provider is an object declared to Angular so that your components, directives, and other classes instantiated by Angular can be injected into its constructor.
4. Create New Module
We can use “ng g module module_name” command to create custom module via Angular CLI
After running this command from terminal, Angular CLI creates new_module.module.ts file in new_module folder under project’s directory structure.
In this story we created module with Angular CLI
If you haven’t read my previous article on Angular Component structure, I recommend you to read it in terms of topic integrity.
See you in the next article…