`:
Form components are often complex. The `ContactComponent` has its own `ContactService`
and [custom pipe](guide/pipes#custom-pipes) (called `Awesome`),
and an alternative version of the `HighlightDirective`.
To make it manageable, place all contact-related material in an `src/app/contact` folder
and break the component into three constituent HTML, TypeScript, and css files:
In the middle of the component template,
notice the two-way data binding `[(ngModel)]`.
`ngModel` is the selector for the `NgModel` directive.
Although `NgModel` is an Angular directive, the _Angular compiler_ won't recognize it for the following reasons:
* `AppModule` doesn't declare `NgModel`.
* `NgModel` wasn't imported via `BrowserModule`.
Even if Angular somehow recognized `ngModel`,
`ContactComponent` wouldn't behave like an Angular form because
form features such as validation aren't yet available.
### Import the FormsModule
Add the `FormsModule` to the `AppModule` metadata's `imports` list.
Now `[(ngModel)]` binding will work and the user input will be validated by Angular forms,
once you declare the new component, pipe, and directive.
*Do not* add `NgModel`—or the `FORMS_DIRECTIVES`—to
the `AppModule` metadata's declarations.
These directives belong to the `FormsModule`.
Components, directives, and pipes belong to _one module only_.
*Never re-declare classes that belong to another module.*
{@a declare-pipe}
### Declare the contact component, directive, and pipe
The application won't compile until you declare the contact component, directive, and pipe.
Update the `declarations` in the `AppModule` accordingly:
{@a import-name-conflict}
There are two directives with the same name, both called `HighlightDirective`.
To work around this, create an alias for the contact version using the `as` JavaScript import keyword.
This solves the immediate issue of referencing both directive _types_ in the same file but
leaves another issue unresolved.
You'll learn more about that issue later in this page, in [Resolve directive conflicts](guide/ngmodule#resolve-conflicts).
### Provide the _ContactService_
The `ContactComponent` displays contacts retrieved by the `ContactService`,
which Angular injects into its constructor.
You have to provide that service somewhere.
The `ContactComponent` could provide it,
but then the service would be scoped to this component only.
You want to share this service with other contact-related components that you'll surely add later.
In this app, add `ContactService` to the `AppModule` metadata's `providers` list:
Now you can inject `ContactService` (like `UserService`) into any component in the application.
{@a application-scoped-providers}
### Application-scoped providers
The `ContactService` provider is _application_-scoped because Angular
registers a module's `providers` with the application's *root injector*.
Architecturally, the `ContactService` belongs to the Contact business domain.
Classes in other domains don't need the `ContactService` and shouldn't inject it.
You might expect Angular to offer a _module_-scoping mechanism to enforce this design.
It doesn't. NgModule instances, unlike components, don't have their own injectors
so they can't have their own provider scopes.
This omission is intentional.
NgModules are designed primarily to extend an application,
to enrich the entire app with the module's capabilities.
In practice, service scoping is rarely an issue.
Non-contact components can't accidentally inject the `ContactService`.
To inject `ContactService`, you must first import its _type_.
Only Contact components should import the `ContactService` type.
Read more in the [How do I restrict service scope to a module?](cookbook/ngmodule-faq#q-component-scoped-providers) section
of the [NgModule FAQs](cookbook/ngmodule-faq) page.
### Run the app
Everything is in place to run the application with its contact editor.
The app file structure looks like this:
app
app.component.ts
app.module.ts
highlight.directive.ts
title.component.(html|ts)
user.service.ts
contact
awesome.pipe.ts
contact.component.(css|html|ts)
contact.service.ts
highlight.directive.ts
Try the example:
{@a resolve-conflicts}
## Resolve directive conflicts
An issue arose [earlier](guide/ngmodule#import-name-conflict) when you declared the contact's `HighlightDirective` because
you already had a `HighlightDirective` class at the application level.
The selectors of the two directives both highlight the attached element with a different color.
Both directives are declared in this module so both directives are active.
When the two directives compete to color the same element,
the directive that's declared later wins because its DOM changes overwrite the first.
In this case, the contact's `HighlightDirective` makes the application title text blue
when it should stay gold.
The issue is that two different classes are trying to do the same thing.
It's OK to import the same directive class multiple times.
Angular removes duplicate classes and only registers one of them.
But from Angular's perspective, two different classes, defined in different files, that have the same name
are not duplicates. Angular keeps both directives and
they take turns modifying the same HTML element.
At least the app still compiles.
If you define two different component classes with the same selector specifying the same element tag,
the compiler reports an error. It can't insert two components in the same DOM location.
To eliminate component and directive conflicts, create feature modules
that insulate the declarations in one module from the declarations in another.
{@a feature-modules}
## Feature modules
This application isn't big yet, but it's already experiencing structural issues.
* The root `AppModule` grows larger with each new application class.
* There are conflicting directives.
The `HighlightDirective` in the contact re-colors the work done by the `HighlightDirective` declared in `AppModule`.
Also, it colors the application title text when it should color only the `ContactComponent`.
* The app lacks clear boundaries between contact functionality and other application features.
That lack of clarity makes it harder to assign development responsibilities to different teams.
You can resolve these issues with _feature modules_.
A feature module is a class adorned by the `@NgModule` decorator and its metadata,
just like a root module.
Feature module metadata have the same properties as the metadata for a root module.
The root module and the feature module share the same execution context.
They share the same dependency injector, which means the services in one module
are available to all.
The modules have the following significant technical differences:
* You _boot_ the root module to _launch_ the app;
you _import_ a feature module to _extend_ the app.
* A feature module can expose or hide its implementation from other modules.
Otherwise, a feature module is distinguished primarily by its intent.
A feature module delivers a cohesive set of functionality
focused on an application business domain, user workflow, facility (forms, http, routing),
or collection of related utilities.
While you can do everything within the root module,
feature modules help you partition the app into areas of specific interest and purpose.
A feature module collaborates with the root module and with other modules
through the services it provides and
the components, directives, and pipes that it shares.
In the next section, you'll carve the contact functionality out of the root module
and into a dedicated feature module.
{@a contact-module-v1}
### Make _Contact_ a feature module
It's easy to refactor the contact material into a contact feature module.
1. Create the `ContactModule` in the `src/app/contact` folder.
1. Move the contact material from `AppModule` to `ContactModule`.
1. Replace the imported `BrowserModule` with `CommonModule`.
1. Import the `ContactModule` into the `AppModule`.
`AppModule` is the only existing class that changes. But you do add one new file.
### Add the _ContactModule_
Here's the new `ContactModule`:
You copy from `AppModule` the contact-related import statements and `@NgModule` properties
that concern the contact, and paste them into `ContactModule`.
You _import_ the `FormsModule` because the contact component needs it.
Modules don't inherit access to the components, directives, or pipes that are declared in other modules.
What `AppModule` imports is irrelevant to `ContactModule` and vice versa.
Before `ContactComponent` can bind with `[(ngModel)]`, its `ContactModule` must import `FormsModule`.
You also replaced `BrowserModule` by `CommonModule`, for reasons explained in the
[Should I import BrowserModule or CommonModule?](cookbook/ngmodule-faq#q-browser-vs-common-module)
section of the [NgModule FAQs](cookbook/ngmodule-faq) page.
You _declare_ the contact component, directive, and pipe in the module `declarations`.
You _export_ the `ContactComponent` so
other modules that import the `ContactModule` can include it in their component templates.
All other declared contact classes are private by default.
The `AwesomePipe` and `HighlightDirective` are hidden from the rest of the application.
The `HighlightDirective` can no longer color the `AppComponent` title text.
### Refactor the _AppModule_
Return to the `AppModule` and remove everything specific to the contact feature set.
* Delete the contact import statements.
* Delete the contact declarations and contact providers.
* Delete the `FormsModule` from the `imports` list (`AppComponent` doesn't need it).
Leave only the classes required at the application root level.
Then import the `ContactModule` so the app can continue to display the exported `ContactComponent`.
Here's the refactored version of the `AppModule` along with the previous version.
### Improvements
There's a lot to like in the revised `AppModule`.
* It does not change as the _Contact_ domain grows.
* It only changes when you add new modules.
* It's simpler:
* Fewer import statements.
* No `FormsModule` import.
* No contact-specific declarations.
* No `ContactService` provider.
* No `HighlightDirective` conflict.
Try this `ContactModule` version of the sample.
Try the live example.
{@a lazy-load}
## Lazy-loading modules with the router
The Heroic Staffing Agency sample app has evolved.
It has two more modules, one for managing the heroes on staff and another for matching crises to the heroes.
Both modules are in the early stages of development.
Their specifics aren't important to the story and this page doesn't discuss every line of code.
Examine and download the complete source for this version from
the live example.
Some facets of the current application merit discussion are as follows:
* The app has three feature modules: Contact, Hero, and Crisis.
* The Angular router helps users navigate among these modules.
* The `ContactComponent` is the default destination when the app starts.
* The `ContactModule` continues to be "eagerly" loaded when the application starts.
* `HeroModule` and the `CrisisModule` are lazy loaded.
{@a app-component-template}
The new `AppComponent` template has
a title, three links, and a ``.
The `` element is gone; you're routing to the _Contact_ page now.
The `AppModule` has changed modestly:
Some file names bear a `.3` extension that indicates
a difference with prior or future versions.
The significant differences will be explained in due course.
The module still imports `ContactModule` so that its routes and components are mounted when the app starts.
The module does _not_ import `HeroModule` or `CrisisModule`.
They'll be fetched and mounted asynchronously when the user navigates to one of their routes.
The significant change from version 2 is the addition of the *AppRoutingModule* to the module `imports`.
The `AppRoutingModule` is a [routing module](guide/router#routing-module)
that handles the app's routing concerns.
### App routing
The router is the subject of the [Routing & Navigation](guide/router) page, so this section skips many of the details and
concentrates on the intersection of NgModules and routing.
The `app-routing.module.ts` file defines three routes.
The first route redirects the empty URL (such as `http://host.com/`)
to another route whose path is `contact` (such as `http://host.com/contact`).
The `contact` route isn't defined here.
It's defined in the _Contact_ feature's _own_ routing module, `contact-routing.module.ts`.
It's standard practice for feature modules with routing components to define their own routes.
You'll get to that file in a moment.
The remaining two routes use lazy loading syntax to tell the router where to find the modules:
A lazy-loaded module location is a _string_, not a _type_.
In this app, the string identifies both the module _file_ and the module _class_,
the latter separated from the former by a `#`.
### RouterModule.forRoot
The `forRoot` static class method of the `RouterModule` with the provided configuration and
added to the `imports` array provides the routing concerns for the module.
The returned `AppRoutingModule` class is a `Routing Module` containing both the `RouterModule` directives
and the dependency-injection providers that produce a configured `Router`.
This `AppRoutingModule` is intended for the app _root_ module only.
Never call `RouterModule.forRoot` in a feature-routing module.
Back in the root `AppModule`, add the `AppRoutingModule` to its `imports` list,
and the app is ready to navigate.
### Routing to a feature module
The `src/app/contact` folder holds a new file, `contact-routing.module.ts`.
It defines the `contact` route mentioned earlier and provides a `ContactRoutingModule` as follows:
This time you pass the route list to the `forChild` method of the `RouterModule`.
The route list is only responsible for providing additional routes and is intended for feature modules.
Always call `RouterModule.forChild` in a feature-routing module.
_forRoot_ and _forChild_ are conventional names for methods that
deliver different `import` values to root and feature modules.
Angular doesn't recognize them but Angular developers do.
[Follow this convention](cookbook/ngmodule-faq#q-for-root) if you write a similar module
that has both shared [declarables](cookbook/ngmodule-faq#q-declarable) and services.
`ContactModule` has changed in two small but important ways.
* It imports the `ContactRoutingModule` object from `contact-routing.module.ts`.
* It no longer exports `ContactComponent`.
Now that you navigate to `ContactComponent` with the router, there's no reason to make it public.
Also, `ContactComponent` doesn't need a selector.
No template will ever again reference this `ContactComponent`.
It's gone from the [AppComponent template](guide/ngmodule#app-component-template).
{@a hero-module}
### Lazy-loaded routing to a module
The lazy-loaded `HeroModule` and `CrisisModule` follow the same principles as any feature module.
They don't look different from the eagerly loaded `ContactModule`.
The `HeroModule` is a bit more complex than the `CrisisModule`, which makes it
a more interesting and useful example. Its file structure is as follows:
hero
hero-detail.component.ts
hero-list.component.ts
hero.component.ts
hero.module.ts
hero-routing.module.ts
hero.service.ts
highlight.directive.ts
This is the child routing scenario familiar to readers of the
[Child routing component](guide/router#child-routing-component) section of the
[Routing & Navigation](guide/router#child-routing-component) page.
The `HeroComponent` is the feature's top component and routing host.
Its template has a `` that displays either a list of heroes (`HeroList`)
or an editor of a selected hero (`HeroDetail`).
Both components delegate to the `HeroService` to fetch and save data.
Yet another `HighlightDirective` colors elements in yet a different shade.
In the next section, [Shared modules](guide/ngmodule#shared-module "Shared modules"), you'll resolve the repetition and inconsistencies.
The `HeroModule` is a feature module like any other.
It imports the `FormsModule` because the `HeroDetailComponent` template binds with `[(ngModel)]`.
It imports the `HeroRoutingModule` from `hero-routing.module.ts` just as `ContactModule` and `CrisisModule` do.
The `CrisisModule` is much the same.
Try the live example.
{@a shared-module}
## Shared modules
The app is shaping up.
But it carries three different versions of the `HighlightDirective`.
And the many files cluttering the app folder level could be better organized.
Add a `SharedModule` to hold the common components, directives, and pipes
and share them with the modules that need them.
1. Create an `src/app/shared` folder.
1. Move the `AwesomePipe` and `HighlightDirective` from `src/app/contact` to `src/app/shared`.
1. Delete the `HighlightDirective` classes from `src/app/` and `src/app/hero`.
1. Create a `SharedModule` class to own the shared material.
1. Update other feature modules to import `SharedModule`.
Here is the `SharedModule`:
Note the following:
* It imports the `CommonModule` because its component needs common directives.
* It declares and exports the utility pipe, directive, and component classes as expected.
* It re-exports the `CommonModule` and `FormsModule`
### Re-exporting other modules
If you review the application, you may notice that many components requiring `SharedModule` directives
also use `NgIf` and `NgFor` from `CommonModule`
and bind to component properties with `[(ngModel)]`, a directive in the `FormsModule`.
Modules that declare these components would have to import `CommonModule`, `FormsModule`, and `SharedModule`.
You can reduce the repetition by having `SharedModule` re-export `CommonModule` and `FormsModule`
so that importers of `SharedModule` get `CommonModule` and `FormsModule` for free.
As it happens, the components declared by `SharedModule` itself don't bind with `[(ngModel)]`.
Technically, there is no need for `SharedModule` to import `FormsModule`.
`SharedModule` can still export `FormsModule` without listing it among its `imports`.
### Why _TitleComponent_ isn't shared
`SharedModule` exists to make commonly used components, directives, and pipes available
for use in the templates of components in many other modules.
The `TitleComponent` is used only once by the `AppComponent`.
There's no point in sharing it.
{@a no-shared-module-providers}
### Why _UserService_ isn't shared
While many components share the same service instances,
they rely on Angular dependency injection to do this kind of sharing, not the module system.
Several components of the sample inject the `UserService`.
There should be only one instance of the `UserService` in the entire application
and only one provider of it.
`UserService` is an application-wide singleton.
You don't want each module to have its own separate instance.
Yet there is [a real danger](cookbook/ngmodule-faq#q-why-it-is-bad) of that happening
if the `SharedModule` provides the `UserService`.
Do *not* specify app-wide singleton `providers` in a shared module.
A lazy-loaded module that imports that shared module makes its own copy of the service.
{@a core-module}
## The Core module
At the moment, the root folder is cluttered with the `UserService`
and `TitleComponent` that only appear in the root `AppComponent`.
You didn't include them in the `SharedModule` for reasons just explained.
Instead, gather them in a single `CoreModule` that you import once when the app starts
and never import anywhere else.
Perform the following steps:
1. Create an `src/app/core` folder.
* Move the `UserService` and `TitleComponent` from `src/app/` to `src/app/core`.
* Create a `CoreModule` class to own the core material.
* Update the `AppRoot` module to import `CoreModule`.
Most of this work is familiar. The interesting part is the `CoreModule`.
You're importing some extra symbols from the Angular core library that you're not using yet.
They'll become relevant later in this page.
The `@NgModule` metadata should be familiar.
You declare the `TitleComponent` because this module owns it and you export it
because `AppComponent` (which is in `AppModule`) displays the title in its template.
`TitleComponent` needs the Angular `NgIf` directive that you import from `CommonModule`.
`CoreModule` provides the `UserService`. Angular registers that provider with the app root injector,
making a singleton instance of the `UserService` available to any component that needs it,
whether that component is eagerly or lazily loaded.
### Why bother?
This scenario is clearly contrived.
The app is too small to worry about a single service file and a tiny, one-time component.
A `TitleComponent` sitting in the root folder isn't bothering anyone.
The root `AppModule` can register the `UserService` itself,
as it does currently, even if you decide to relocate the `UserService` file to the `src/app/core` folder.
Real-world apps have more to worry about.
They can have several single-use components (such as spinners, message toasts, and modal dialogs)
that appear only in the `AppComponent` template.
You don't import them elsewhere so they're not shared in that sense.
Yet they're too big and messy to leave loose in the root folder.
Apps often have many singleton services like this sample's `UserService`.
Each must be registered exactly once, in the app root injector, when the application starts.
While many components inject such services in their constructors—and
therefore require JavaScript `import` statements to import their symbols—no
other component or module should define or re-create the services themselves.
Their _providers_ aren't shared.
We recommend collecting such single-use classes and hiding their details inside a `CoreModule`.
A simplified root `AppModule` imports `CoreModule` in its capacity as orchestrator of the application as a whole.
## Cleanup
Having refactored to a `CoreModule` and a `SharedModule`, it's time to clean up the other modules.
### A trimmer _AppModule_
Here is the updated `AppModule` paired with version 3 for comparison:
`AppModule` now has the following qualities:
* A little smaller because many `src/app/root` classes have moved to other modules.
* Stable because you'll add future components and providers to other modules, not this one.
* Delegated to imported modules rather than doing work.
* Focused on its main task, orchestrating the app as a whole.
### A trimmer _ContactModule_
Here is the new `ContactModule` paired with the prior version:
Notice the following:
* The `AwesomePipe` and `HighlightDirective` are gone.
* The imports include `SharedModule` instead of `CommonModule` and `FormsModule`.
* The new version is leaner and cleaner.
{@a core-for-root}
## Configure core services with _CoreModule.forRoot_
A module that adds providers to the application can offer a facility for configuring those providers as well.
By convention, the `forRoot` static method both provides and configures services at the same time.
It takes a service configuration object and returns a
[ModuleWithProviders](api/core/index/ModuleWithProviders-interface), which is
a simple object with the following properties:
* `ngModule`: the `CoreModule` class
* `providers`: the configured providers
The root `AppModule` imports the `CoreModule` and adds the `providers` to the `AppModule` providers.
More precisely, Angular accumulates all imported providers before appending the items listed in `@NgModule.providers`.
This sequence ensures that whatever you add explicitly to the `AppModule` providers takes precedence
over the providers of imported modules.
Add a `CoreModule.forRoot` method that configures the core `UserService`.
You've extended the core `UserService` with an optional, injected `UserServiceConfig`.
If a `UserServiceConfig` exists, the `UserService` sets the user name from that config.
Here's `CoreModule.forRoot` that takes a `UserServiceConfig` object:
Lastly, call it within the `imports` list of the `AppModule`.
The app displays "Miss Marple" as the user instead of the default "Sherlock Holmes".
Call `forRoot` only in the root application module, `AppModule`.
Calling it in any other module, particularly in a lazy-loaded module,
is contrary to the intent and can produce a runtime error.
Remember to _import_ the result; don't add it to any other `@NgModule` list.
{@a prevent-reimport}
## Prevent reimport of the _CoreModule_
Only the root `AppModule` should import the `CoreModule`.
[Bad things happen](cookbook/ngmodule-faq#q-why-it-is-bad) if a lazy-loaded module imports it.
You could hope that no developer makes that mistake.
Or you can guard against it and fail fast by adding the following `CoreModule` constructor.
The constructor tells Angular to inject the `CoreModule` into itself.
That seems dangerously circular.
The injection would be circular if Angular looked for `CoreModule` in the _current_ injector.
The `@SkipSelf` decorator means "look for `CoreModule` in an ancestor injector, above me in the injector hierarchy."
If the constructor executes as intended in the `AppModule`,
there is no ancestor injector that could provide an instance of `CoreModule`.
The injector should give up.
By default, the injector throws an error when it can't find a requested provider.
The `@Optional` decorator means not finding the service is OK.
The injector returns `null`, the `parentModule` parameter is null,
and the constructor concludes uneventfully.
It's a different story if you improperly import `CoreModule` into a lazy-loaded module such as `HeroModule` (try it).
Angular creates a lazy-loaded module with its own injector, a _child_ of the root injector.
`@SkipSelf` causes Angular to look for a `CoreModule` in the parent injector, which this time is the root injector.
Of course it finds the instance imported by the root `AppModule`.
Now `parentModule` exists and the constructor throws the error.
### Conclusion
You made it! You can examine and download the complete source for this final version from the live example.
### Frequently asked questions
Now that you understand NgModules, you may be interested
in the companion [NgModule FAQs](cookbook/ngmodule-faq "NgModule FAQs") page
with its ready answers to specific design and implementation questions.