Module
Root Module & Functional Module
Every Angular app has at least one NgModule class, a root module
, conventionally named AppModule
and resides in a file named app.module.ts
, which provides the bootstrap mechanism that launches the application. You launch your app by bootstrapping the root NgModule.
An app typically contains many functional modules
/ feature modules
.
Advantage of Modulization
Organizing your code into distinct functional modules helps in managing development of complex applications, and in designing for reusability. In addition, this technique lets you take advantage of lazy-loading
—that is, loading modules on demand—in order to minimize the amount aof code that needs to be loaded at startup.
Root Module (NgModule)
An NgModule is defined as a class decorated with @NgModule. The most important properties are as follows.
declarations—此 module 中定義的 components, directives, and pipes .
exports—要 export 出去讓別的 module 可 reuse. A root NgModule has no reason to export anything because other modules don't need to import the root NgModule.
imports—此 module 中的 component / template 需使用其他 module 的東西,需在此 import.
providers—Creators of services that this NgModule contributes to the global collection of services; they become accessible in all parts of the app. (大多時候會將 providers 定義在 component level.)
bootstrap—The main application view, called the root component, which hosts all other app views. Only the root NgModule should set this bootstrap property.
A root NgModule always has a root component that is created during bootstrap, but any NgModule can include any number of additional components, which can be loaded through the router or created through the template.
Must import BrowserModule
which includes CommonModule
.
Function Module / Feature
A component can contain a view hierarchy. A view hierarchy can mix views defined in components that belong to different NgModules.
When you create a component, it is associated directly with a single view, called the host view
. The host view can be the root of a view hierarchy, which can contain embedded views, which are in turn the host views of other components. Those components can be in the same NgModule, or can be imported from other NgModules. Views in the tree can be nested to any depth.
Must importCommonModule
.
Lazy Load Module
Each “View Module” (let’s call it this way) can be lazy loaded by the router, I already mentioned that in an article.
Providers
You must register at least one_provider_of any service you are going to use. You can register providers in modules or in components.
When you register a provider at the component level, you get a new instance of the service with each new instance of that component. At the component level, register a service provider in the providers property of the @Component metadata:
Last updated
Was this helpful?