{ "id": "guide/ngmodule-faq", "title": "NgModule FAQ", "contents": "\n\n\n
NgModules help organize an application into cohesive blocks of functionality.
\nThis page answers the questions many developers ask about NgModule design and implementation.
\ndeclarations
array?linkAdd declarable classes—components, directives, and pipes—to a declarations
list.
Declare these classes in exactly one module of the application.\nDeclare them in a module if they belong to that particular module.
\n\nDeclarables are the class types—components, directives, and pipes—that\nyou can add to a module's declarations
list.\nThey're the only classes that you can add to declarations
.
declarations
?linkAdd only declarable classes to an NgModule's declarations
list.
Do not declare the following:
\nA class that's already declared in another module, whether an app module, @NgModule, or third-party module.
\nAn array of directives imported from another module.\nFor example, don't declare FORMS_DIRECTIVES
from @angular/forms
because the FormsModule
already declares it.
Module classes.
\nService classes.
\nNon-Angular classes and objects, such as\nstrings, numbers, functions, entity models, configurations, business logic, and helper classes.
\nNgModule
properties?linkAppComponent
is often listed in both declarations
and bootstrap
.\nYou might see the same component listed in declarations
, exports
, and entryComponents
.
While that seems redundant, these properties have different functions.\nMembership in one list doesn't imply membership in another list.
\nAppComponent
could be declared in this module but not bootstrapped.AppComponent
could be bootstrapped in this module but declared in a different feature module.This error often means that you haven't declared the directive \"x\"\nor haven't imported the NgModule to which \"x\" belongs.
\nPerhaps you declared \"x\" in an application sub-module but forgot to export it.\nThe \"x\" class isn't visible to other modules until you add it to the exports
list.
Import NgModules whose public (exported) declarable classes\nyou need to reference in this module's component templates.
\nThis always means importing CommonModule
from @angular/common
for access to\nthe Angular directives such as NgIf
and NgFor
.\nYou can import it directly or from another NgModule that re-exports it.
Import FormsModule
from @angular/forms
\nif your components have [(ngModel)]
two-way binding expressions.
Import shared and feature modules when this module's components incorporate their\ncomponents, directives, and pipes.
\nImport BrowserModule only in the root AppModule
.
BrowserModule
or CommonModule
?linkThe root application module, AppModule
, of almost every browser application\nshould import BrowserModule
from @angular/platform-browser
.
BrowserModule
provides services that are essential to launch and run a browser app.
BrowserModule
also re-exports CommonModule
from @angular/common
,\nwhich means that components in the AppModule
also have access to\nthe Angular directives every app needs, such as NgIf
and NgFor
.
Do not import BrowserModule
in any other module.\nFeature modules and lazy-loaded modules should import CommonModule
instead.\nThey need the common directives. They don't need to re-install the app-wide providers.
Importing CommonModule
also frees feature modules for use on any target platform, not just browsers.
That's not a problem. When three modules all import Module 'A',\nAngular evaluates Module 'A' once, the first time it encounters it, and doesn't do so again.
\nThat's true at whatever level A
appears in a hierarchy of imported NgModules.\nWhen Module 'B' imports Module 'A', Module 'C' imports 'B', and Module 'D' imports [C, B, A]
,\nthen 'D' triggers the evaluation of 'C', which triggers the evaluation of 'B', which evaluates 'A'.\nWhen Angular gets to the 'B' and 'A' in 'D', they're already cached and ready to go.
Angular doesn't like NgModules with circular references, so don't let Module 'A' import Module 'B', which imports Module 'A'.
\n\nExport declarable classes that components in other NgModules\nare able to reference in their templates. These are your public classes.\nIf you don't export a declarable class, it stays private, visible only to other components\ndeclared in this NgModule.
\nYou can export any declarable class—components, directives, and pipes—whether\nit's declared in this NgModule or in an imported NgModule.
\nYou can re-export entire imported NgModules, which effectively re-export all of their exported classes.\nAn NgModule can even export a module that it doesn't import.
\nDon't export the following:
\nHttpClientModule
because it doesn't export anything.\nIts only purpose is to add http service providers to the application as a whole.Absolutely.
\nNgModules are a great way to selectively aggregate classes from other NgModules and\nre-export them in a consolidated, convenience module.
\nAn NgModule can re-export entire NgModules, which effectively re-exports all of their exported classes.\nAngular's own BrowserModule
exports a couple of NgModules like this:
An NgModule can export a combination of its own declarations, selected imported classes, and imported NgModules.
\nDon't bother re-exporting pure service modules.\nPure service modules don't export declarable classes that another NgModule could use.\nFor example, there's no point in re-exporting HttpClientModule
because it doesn't export anything.\nIts only purpose is to add http service providers to the application as a whole.
forRoot()
method?linkThe forRoot()
static method is a convention that makes it easy for developers to configure services and providers that are intended to be singletons. A good example of forRoot()
is the RouterModule.forRoot()
method.
Apps pass a Routes
array to RouterModule.forRoot()
in order to configure the app-wide Router
service with routes.\nRouterModule.forRoot()
returns a ModuleWithProviders.\nYou add that result to the imports
list of the root AppModule
.
Only call and import a forRoot()
result in the root application module, AppModule
.\nAvoid importing it in any other module, particularly in a lazy-loaded module. For more\ninformation on forRoot()
see the forRoot()
pattern section of the Singleton Services guide.
For a service, instead of using forRoot()
, specify providedIn: 'root'
on the service's @Injectable()
decorator, which\nmakes the service automatically available to the whole application and thus singleton by default.
RouterModule
also offers a forChild()
static method for configuring the routes of lazy-loaded modules.
forRoot()
and forChild()
are conventional names for methods that\nconfigure services in root and feature modules respectively.
Follow this convention when you write similar modules with configurable service providers.
\nProviders listed in the @NgModule.providers
of a bootstrapped module have application scope.\nAdding a service provider to @NgModule.providers
effectively publishes the service to the entire application.
When you import an NgModule,\nAngular adds the module's service providers (the contents of its providers
list)\nto the application root injector.
This makes the provider visible to every class in the application that knows the provider's lookup token, or name.
\nExtensibility through NgModule imports is a primary goal of the NgModule system.\nMerging NgModule providers into the application injector\nmakes it easy for a module library to enrich the entire application with new services.\nBy adding the HttpClientModule
once, every application component can make HTTP requests.
However, this might feel like an unwelcome surprise if you expect the module's services\nto be visible only to the components declared by that feature module.\nIf the HeroModule
provides the HeroService
and the root AppModule
imports HeroModule
,\nany class that knows the HeroService
type can inject that service,\nnot just the classes declared in the HeroModule
.
To limit access to a service, consider lazy loading the NgModule that provides that service. See How do I restrict service scope to a module? for more information.
\n\nUnlike providers of the modules loaded at launch,\nproviders of lazy-loaded modules are module-scoped.
\nWhen the Angular router lazy-loads a module, it creates a new execution context.\nThat context has its own injector,\nwhich is a direct child of the application injector.
\nThe router adds the lazy module's providers and the providers of its imported NgModules to this child injector.
\nThese providers are insulated from changes to application providers with the same lookup token.\nWhen the router creates a component within the lazy-loaded context,\nAngular prefers service instances created from these providers to the service instances of the application root injector.
\nWhen two imported modules, loaded at the same time, list a provider with the same token,\nthe second module's provider \"wins\". That's because both providers are added to the same injector.
\nWhen Angular looks to inject a service for that token,\nit creates and delivers the instance created by the second provider.
\nEvery class that injects this service gets the instance created by the second provider.\nEven classes declared within the first module get the instance created by the second provider.
\nIf NgModule A provides a service for token 'X' and imports an NgModule B\nthat also provides a service for token 'X', then NgModule A's service definition \"wins\".
\nThe service provided by the root AppModule
takes precedence over services provided by imported NgModules.\nThe AppModule
always wins.
When a module is loaded at application launch,\nits @NgModule.providers
have application-wide scope;\nthat is, they are available for injection throughout the application.
Imported providers are easily replaced by providers from another imported NgModule.\nSuch replacement might be by design. It could be unintentional and have adverse consequences.
\nAs a general rule, import modules with providers exactly once, preferably in the application's root module.\nThat's also usually the best place to configure, wrap, and override them.
\nSuppose a module requires a customized HttpBackend
that adds a special header for all Http requests.\nIf another module elsewhere in the application also customizes HttpBackend
\nor merely imports the HttpClientModule
, it could override this module's HttpBackend
provider,\nlosing the special header. The server will reject http requests from this module.
To avoid this problem, import the HttpClientModule
only in the AppModule
, the application root module.
If you must guard against this kind of \"provider corruption\", don't rely on a launch-time module's providers
.
Load the module lazily if you can.\nAngular gives a lazy-loaded module its own child injector.\nThe module's providers are visible only within the component tree created with this injector.
\nIf you must load the module eagerly, when the application starts,\nprovide the service in a component instead.
\nContinuing with the same example, suppose the components of a module truly require a private, custom HttpBackend
.
Create a \"top component\" that acts as the root for all of the module's components.\nAdd the custom HttpBackend
provider to the top component's providers
list rather than the module's providers
.\nRecall that Angular creates a child injector for each component instance and populates the injector\nwith the component's own providers.
When a child of this component asks for the HttpBackend
service,\nAngular provides the local HttpBackend
service,\nnot the version provided in the application root injector.\nChild components make proper HTTP requests no matter what other modules do to HttpBackend
.
Be sure to create module components as children of this module's top component.
\nYou can embed the child components in the top component's template.\nAlternatively, make the top component a routing host by giving it a <router-outlet>
.\nDefine child routes and let the router load module components into that outlet.
Though you can limit access to a service by providing it in a lazy loaded module or providing it in a component, providing services in a component can lead to multiple instances of those services. Thus, the lazy loading is preferable.
\n\nAppModule
or the root AppComponent
?link Define application-wide providers by specifying providedIn: 'root'
on its @Injectable()
decorator (in the case of services) or at InjectionToken
construction (in the case where tokens are provided). Providers that are created this way automatically are made available to the entire application and don't need to be listed in any module.
If a provider cannot be configured in this way (perhaps because it has no sensible default value), then register application-wide providers in the root AppModule
, not in the AppComponent
.
Lazy-loaded modules and their components can inject AppModule
services;\nthey can't inject AppComponent
services.
Register a service in AppComponent
providers only if the service must be hidden\nfrom components outside the AppComponent
tree. This is a rare use case.
More generally, prefer registering providers in NgModules to registering in components.
\nAngular registers all startup module providers with the application root injector.\nThe services that root injector providers create have application scope, which\nmeans they are available to the entire application.
\nCertain services, such as the Router
, only work when you register them in the application root injector.
By contrast, Angular registers AppComponent
providers with the AppComponent
's own injector.\nAppComponent
services are available only to that component and its component tree.\nThey have component scope.
The AppComponent
's injector is a child of the root injector, one down in the injector hierarchy.\nFor applications that don't use the router, that's almost the entire application.\nBut in routed applications, routing operates at the root level\nwhere AppComponent
services don't exist.\nThis means that lazy-loaded modules can't reach them.
Providers should be configured using @Injectable
syntax. If possible, they should be provided in the application root (providedIn: 'root'
). Services that are configured this way are lazily loaded if they are only used from a lazily loaded context.
If it's the consumer's decision whether a provider is available application-wide or not,\nthen register providers in modules (@NgModule.providers
) instead of registering in components (@Component.providers
).
Register a provider with a component when you must limit the scope of a service instance\nto that component and its component tree.\nApply the same reasoning to registering a provider with a directive.
\nFor example, an editing component that needs a private copy of a caching service should register\nthe service with the component.\nThen each new instance of the component gets its own cached service instance.\nThe changes that editor makes in its service don't touch the instances elsewhere in the application.
\nAlways register application-wide services with the root AppModule
,\nnot the root AppComponent
.
When an eagerly loaded module provides a service, for example a UserService
, that service is available application-wide. If the root module provides UserService
and\nimports another module that provides the same UserService
, Angular registers one of\nthem in the root app injector (see What if I import the same module twice?).
Then, when some component injects UserService
, Angular finds it in the app root injector,\nand delivers the app-wide singleton service. No problem.
Now consider a lazy loaded module that also provides a service called UserService
.
When the router lazy loads a module, it creates a child injector and registers the UserService
\nprovider with that child injector. The child injector is not the root injector.
When Angular creates a lazy component for that module and injects UserService
,\nit finds a UserService
provider in the lazy module's child injector\nand creates a new instance of the UserService
.\nThis is an entirely different UserService
instance\nthan the app-wide singleton version that Angular injected in one of the eagerly loaded components.
This scenario causes your app to create a new instance every time, instead of using the singleton.
\n\n\nAngular adds @NgModule.providers
to the application root injector, unless the NgModule is lazy-loaded.\nFor a lazy-loaded NgModule, Angular creates a child injector and adds the module's providers to the child injector.
This means that an NgModule behaves differently depending on whether it's loaded during application start\nor lazy-loaded later. Neglecting that difference can lead to adverse consequences.
\nWhy doesn't Angular add lazy-loaded providers to the app root injector as it does for eagerly loaded NgModules?
\nThe answer is grounded in a fundamental characteristic of the Angular dependency-injection system.\nAn injector can add providers until it's first used.\nOnce an injector starts creating and delivering services, its provider list is frozen; no new providers are allowed.
\nWhen an applications starts, Angular first configures the root injector with the providers of all eagerly loaded NgModules\nbefore creating its first component and injecting any of the provided services.\nOnce the application begins, the app root injector is closed to new providers.
\nTime passes and application logic triggers lazy loading of an NgModule.\nAngular must add the lazy-loaded module's providers to an injector somewhere.\nIt can't add them to the app root injector because that injector is closed to new providers.\nSo Angular creates a new child injector for the lazy-loaded module context.
\n\nSome NgModules and their services should be loaded only once by the root AppModule
.\nImporting the module a second time by lazy loading a module could produce errant behavior\nthat may be difficult to detect and diagnose.
To prevent this issue, write a constructor that attempts to inject the module or service\nfrom the root app injector. If the injection succeeds, the class has been loaded a second time.\nYou can throw an error or take other remedial action.
\nCertain NgModules, such as BrowserModule
, implement such a guard.\nHere is a custom constructor for an NgModule called GreetingModule
.
entry component
?linkAn entry component is any component that Angular loads imperatively by type.
\nA component loaded declaratively via its selector is not an entry component.
\nAngular loads a component declaratively when\nusing the component's selector to locate the element in the template.\nAngular then creates the HTML representation of the component and inserts it into the DOM at the selected element. These aren't entry components.
\nThe bootstrapped root AppComponent
is an entry component.\nTrue, its selector matches an element tag in index.html
.\nBut index.html
isn't a component template and the AppComponent
\nselector doesn't match an element in any component template.
Components in route definitions are also entry components.\nA route definition refers to a component by its type.\nThe router ignores a routed component's selector, if it even has one, and\nloads the component dynamically into a RouterOutlet
.
For more information, see Entry Components.
\nA bootstrapped component is an entry component\nthat Angular loads into the DOM during the bootstrap process (application launch).\nOther entry components are loaded dynamically by other means, such as with the router.
\nThe @NgModule.bootstrap
property tells the compiler that this is an entry component and\nit should generate code to bootstrap the application with this component.
There's no need to list a component in both the bootstrap
and entryComponents
lists,\nalthough doing so is harmless.
For more information, see Entry Components.
\nMost application developers won't need to add components to the entryComponents
.
Angular adds certain components to entry components automatically.\nComponents listed in @NgModule.bootstrap
are added automatically.\nComponents referenced in router configuration are added automatically.\nThese two mechanisms account for almost all entry components.
If your app happens to bootstrap or dynamically load a component by type in some other manner,\nyou must add it to entryComponents
explicitly.
Although it's harmless to add components to this list,\nit's best to add only the components that are truly entry components.\nDon't include components that are referenced\nin the templates of other components.
\nFor more information, see Entry Components.
\nThe reason is tree shaking. For production apps you want to load the smallest, fastest code possible. The code should contain only the classes that you actually need.\nIt should exclude a component that's never used, whether or not that component is declared.
\nIn fact, many libraries declare and export components you'll never use.\nIf you don't reference them, the tree shaker drops these components from the final code package.
\nIf the Angular compiler generated code for every declared component, it would defeat the purpose of the tree shaker.
\nInstead, the compiler adopts a recursive strategy that generates code only for the components you use.
\nThe compiler starts with the entry components,\nthen it generates code for the declared components it finds in an entry component's template,\nthen for the declared components it discovers in the templates of previously compiled components,\nand so on. At the end of the process, the compiler has generated code for every entry component\nand every component reachable from an entry component.
\nIf a component isn't an entry component or wasn't found in a template,\nthe compiler omits it.
\nEvery app is different. Developers have various levels of experience and comfort with the available choices.\nSome suggestions and guidelines appear to have wide appeal.
\nSharedModule
linkSharedModule
is a conventional name for an NgModule
with the components, directives, and pipes that you use\neverywhere in your app. This module should consist entirely of declarations
,\nmost of them exported.
The SharedModule
may re-export other widget modules, such as CommonModule
,\nFormsModule
, and NgModules with the UI controls that you use most widely.
The SharedModule
should not have providers
for reasons explained previously.\nNor should any of its imported or re-exported modules have providers
.
Import the SharedModule
in your feature modules,\nboth those loaded when the app starts and those you lazy load later.
Feature modules are modules you create around specific application business domains, user workflows, and utility collections. They support your app by containing a particular feature,\nsuch as routes, services, widgets, etc. To conceptualize what a feature module might be in your\napp, consider that if you would put the files related to a certain functionality, like a search,\nin one folder, that the contents of that folder would be a feature module that you might call\nyour SearchModule
. It would contain all of the components, routing, and templates that\nwould make up the search functionality.
For more information, see Feature Modules and\nModule Types
\nIn an Angular app, NgModules and JavaScript modules work together.
\nIn modern JavaScript, every file is a module\n(see the Modules page of the Exploring ES6 website).\nWithin each file you write an export
statement to make parts of the module public.
An Angular NgModule is a class with the @NgModule
decorator—JavaScript modules\ndon't have to have the @NgModule
decorator. Angular's NgModule
has imports
and exports
and they serve a similar purpose.
You import other NgModules so you can use their exported classes in component templates.\nYou export this NgModule's classes so they can be imported and used by components of other NgModules.
\nFor more information, see JavaScript Modules vs. NgModules.
\n\nThe Angular compiler looks inside component templates\nfor other components, directives, and pipes. When it finds one, that's a template reference.
\nThe Angular compiler finds a component or directive in a template when it can match the selector of that component or directive to some HTML in that template.
\nThe compiler finds a pipe if the pipe's name appears within the pipe syntax of the template HTML.
\nAngular only matches selectors and pipe names for classes that are declared by this module\nor exported by a module that this module imports.
\n\nThe Angular compiler converts the application code you write into highly performant JavaScript code.\nThe @NgModule
metadata plays an important role in guiding the compilation process.
The code you write isn't immediately executable. For example, components have templates that contain custom elements, attribute directives, Angular binding declarations,\nand some peculiar syntax that clearly isn't native HTML.
\nThe Angular compiler reads the template markup,\ncombines it with the corresponding component class code, and emits component factories.
\nA component factory creates a pure, 100% JavaScript representation\nof the component that incorporates everything described in its @Component
metadata:\nthe HTML, the binding instructions, the attached styles.
Because directives and pipes appear in component templates,\nthe Angular compiler incorporates them into compiled component code too.
\n@NgModule
metadata tells the Angular compiler what components to compile for this module and\nhow to link this module with other modules.