In a single-page app, you change what the user sees by showing or hiding portions of the display that correspond to particular components, rather than going out to the server to get a new page.
As users perform application tasks, they need to move between the different [views](guide/glossary#view "Definition of view") that you have defined.
To implement this kind of navigation within the single page of your app, you use the Angular **`Router`**.
For an introduction to Angular with a ready-made app, see [Getting Started](start).
For a more in-depth experience of building an Angular app, see the [Tour of Heroes](tutorial) tutorial. Both guide you through using component classes and templates.
The following command uses the Angular CLI to generate a basic Angular app with an app routing module, called `AppRoutingModule`, which is an NgModule where you can configure your routes.
The app name in the following example is `routing-app`.
When generating a new app, the CLI prompts you to select CSS or a CSS preprocessor.
For this example, accept the default of `CSS`.
### Adding components for routing
To use the Angular router, an app needs to have at least two components so that it can navigate from one to the other. To create a component using the CLI, enter the following at the command line where `first` is the name of your component:
The order of routes is important because the `Router` uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes.
List routes with a static path first, followed by an empty path route, which matches the default route.
The [wildcard route](guide/router#setting-up-wildcard-routes) comes last because it matches every URL and the `Router` selects it only if no other routes match first.
The two asterisks, `**`, indicate to Angular that this `routes` definition is a wildcard route.
For the component property, you can define any component in your application.
Common choices include an application-specific `PageNotFoundComponent`, which you can define to [display a 404 page](guide/router#404-page-how-to) to your users; or a redirect to your application's main component.
A wildcard route is the last route because it matches any URL.
For more detail on why order matters for routes, see [Route order](guide/router#route-order).
To display a 404 page, set up a [wildcard route](guide/router#wildcard-route-how-to) with the `component` property set to the component you'd like to use for your 404 page as follows:
The last route with the `path` of `**` is a wildcard route.
The router selects this route if the requested URL doesn't match any of the paths earlier in the list and sends the user to the `PageNotFoundComponent`.
To set up a redirect, configure a route with the `path` you want to redirect from, the `component` you want to redirect to, and a `pathMatch` value that tells the router how to match the URL.
Relative paths allow you to define paths that are relative to the current URL segment.
The following example shows a relative route to another component, `second-component`.
`FirstComponent` and `SecondComponent` are at the same level in the tree, however, the link to `SecondComponent` is situated within the `FirstComponent`, meaning that the router has to go up a level and then into the second directory to find the `SecondComponent`.
Rather than writing out the whole path to get to `SecondComponent`, you can use the `../` notation to go up a level.
After the link parameters array, which here contains `items`, add an object with the `relativeTo` property set to the `ActivatedRoute`, which is `this.route`.
Sometimes, a feature of your application requires accessing a part of a route, such as a query parameter or a fragment. The Tour of Heroes app at this stage in the tutorial uses a list view in which you can click on a hero to see details. The router uses an `id` to show the correct hero's details.
Configure the class so that you have an observable, `heroes$`, a `selectedId` to hold the `id` number of the hero, and the heroes in the `ngOnInit()`, add the following code to get the `id` of the selected hero.
This code snippet assumes that you have a heroes list, a hero service, a function to get your heroes, and the HTML to render your list and details, just as in the Tour of Heroes example.
You can configure your routes to lazy load modules, which means that Angular only loads modules as needed, rather than loading all modules when the app launches.
Additionally, you can preload parts of your app in the background to improve the user experience.
The following minimal `RouterLink` example builds upon a specified [default child route](guide/router-tutorial-toh#a-crisis-center-with-child-routes) for the crisis center.
In summary, you can write applications with one, two or more levels of routing.
The link parameters array affords the flexibility to represent any routing depth and any legal sequence of route paths, (required) router parameters, and (optional) route parameter objects.
Modern HTML5 browsers support <ahref="https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries"title="HTML5 browser history push-state">history.pushState</a>, a technique that changes a browser's location and history without triggering a server page request.
The router can compose a "natural" URL that is indistinguishable from one that would otherwise require a page load.
You must choose a routing strategy early in the development of you project because once the application is in production, visitors to your site use and depend on application URL references.
Rendering critical pages on the server is a technique that can greatly improve perceived responsiveness when the app first loads.
An app that would otherwise take ten or more seconds to start could be rendered on the server and delivered to the user's device in less than a second.
The router uses the browser's <ahref="https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries"title="HTML5 browser history push-state">history.pushState</a> for navigation.
`pushState` allows you to customize in-app URL paths; for example, `localhost:4200/crisis-center`.
The in-app URLs can be indistinguishable from server URLs.
Modern HTML5 browsers were the first to support `pushState` which is why many people refer to these URLs as "HTML5 style" URLs.
In the [LocationStrategy and browser URL styles](#browser-url-styles) section, learn why HTML5 style is preferable, how to adjust its behavior, and how to switch to the older hash (#) style, if necessary.
You must add a <ahref="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base"title="base href"><base href> element</a> to the app's `index.html` for `pushState` routing to work.
The browser uses the `<base href>` value to prefix relative URLs when referencing CSS files, scripts, and images.
While the router uses the <ahref="https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries"title="Browser history push-state">HTML5 pushState</a> style by default, you must configure that strategy with a `<base href>`.
The preferred way to configure the strategy is to add a <ahref="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base"title="base href"><base href> element</a> tag in the `<head>` of the `index.html`.
You can use `HashLocationStrategy` by providing the `useHash: true` in an object as the second argument of the `RouterModule.forRoot()` in the `AppModule`.
The following example creates five route definitions, configures the router via the `RouterModule.forRoot()` method, and adds the result to the `AppModule`'s `imports` array.
The router parses and builds the final URL for you, which allows you to use both relative and absolute paths when navigating between application views.
The `data` property in the third route is a place to store arbitrary data associated with
this specific route.
The data property is accessible within each activated route. Use it to store items such as page titles, breadcrumb text, and other read-only, static data.
The empty path in the fourth route represents the default path for the application—the place to go when the path in the URL is empty, as it typically is at the start.
This default route redirects to the route for the `/heroes` URL and, therefore, displays the `HeroesListComponent`.
If you need to see what events are happening during the navigation lifecycle, there is the `enableTracing` option as part of the router's default configuration.
This outputs each router event that took place during each navigation lifecycle to the browser console.
Use `enableTracing` only for debugging purposes.
You set the `enableTracing: true` option in the object passed as the second argument to the `RouterModule.forRoot()` method.
Given the configuration above, when the browser URL for this application becomes `/heroes`, the router matches that URL to the route path `/heroes` and displays the `HeroListComponent` as a sibling element to the `RouterOutlet` that you've placed in the host component's template.
Had the navigation path been more dynamic, you could have bound to a template expression that returned an array of route link parameters; that is, the [link parameters array](guide/router#link-parameters-array).
The router resolves that array into a complete URL.
On each anchor tag, you see a [property binding](guide/template-syntax#property-binding) to the `RouterLinkActive` directive that looks like `routerLinkActive="..."`.
The template expression to the right of the equal sign, `=`, contains a space-delimited string of CSS classes that the Router adds when this link is active (and removes when the link is inactive).
You set the `RouterLinkActive` directive to a string of classes such as `[routerLinkActive]="'active fluffy'"` or bind it to a component property that returns such a string.
Active route links cascade down through each level of the route tree, so parent and child router links can be active at the same time.
To override this behavior, you can bind to the `[routerLinkActiveOptions]` input binding with the `{ exact: true }` expression. By using `{ exact: true }`, a given `RouterLink` will only be active if its URL is an exact match to the current URL.
After the end of each successful navigation lifecycle, the router builds a tree of `ActivatedRoute` objects that make up the current state of the router. You can access the current `RouterState` from anywhere in the application using the `Router` service and the `routerState` property.
Each `ActivatedRoute` in the `RouterState` provides methods to traverse up and down the route tree to get information from parent, child and sibling routes.
An `Observable` that contains a [map](api/router/ParamMap) of the required and [optional parameters](guide/router-tutorial-toh#optional-route-parameters) specific to the route.
An `Observable` that contains a [map](api/router/ParamMap) of the [query parameters](guide/router-tutorial-toh#query-parameters) available to all routes.
*`params`: An `Observable` that contains the required and [optional parameters](guide/router-tutorial-toh#optional-route-parameters) specific to the route. Use `paramMap` instead.
During each navigation, the `Router` emits navigation events through the `Router.events` property.
These events range from when the navigation starts and ends to many points in between. The full list of navigation events is displayed in the table below.
<table>
<tr>
<th>
Router Event
</th>
<th>
Description
</th>
</tr>
<tr>
<td>
<code>NavigationStart</code>
</td>
<td>
An [event](api/router/NavigationStart) triggered when navigation starts.
</td>
</tr>
<tr>
<td>
<code>RouteConfigLoadStart</code>
</td>
<td>
An [event](api/router/RouteConfigLoadStart) triggered before the `Router`
An [event](api/router/NavigationError) triggered when navigation fails due to an unexpected error.
</td>
</tr>
<tr>
<td>
<code>Scroll</code>
</td>
<td>
An [event](api/router/Scroll) that represents a scrolling event.
</td>
</tr>
</table>
When you enable the `enableTracing` option, Angular logs these events to the console.
For an example of filtering router navigation events, see the [router section](guide/observables-in-angular#router) of the [Observables in Angular](guide/observables-in-angular) guide.
### Router terminology
Here are the key `Router` terms and their meanings:
<table>
<tr>
<th>
Router Part
</th>
<th>
Meaning
</th>
</tr>
<tr>
<td>
<code>Router</code>
</td>
<td>
Displays the application component for the active URL.
Manages navigation from one component to the next.
</td>
</tr>
<tr>
<td>
<code>RouterModule</code>
</td>
<td>
A separate NgModule that provides the necessary service providers
and directives for navigating through application views.
</td>
</tr>
<tr>
<td>
<code>Routes</code>
</td>
<td>
Defines an array of Routes, each mapping a URL path to a component.
</td>
</tr>
<tr>
<td>
<code>Route</code>
</td>
<td>
Defines how the router should navigate to a component based on a URL pattern.
Most routes consist of a path and a component type.
</td>
</tr>
<tr>
<td>
<code>RouterOutlet</code>
</td>
<td>
The directive (<code><router-outlet></code>) that marks where the router displays a view.
</td>
</tr>
<tr>
<td>
<code>RouterLink</code>
</td>
<td>
The directive for binding a clickable HTML element to a route. Clicking an element with a <code>routerLink</code> directive that is bound to a <i>string</i> or a <i>link parameters array</i> triggers a navigation.
</td>
</tr>
<tr>
<td>
<code>RouterLinkActive</code>
</td>
<td>
The directive for adding/removing classes from an HTML element when an associated <code>routerLink</code> contained on or inside the element becomes active/inactive.
</td>
</tr>
<tr>
<td>
<code>ActivatedRoute</code>
</td>
<td>
A service that is provided to each route component that contains route specific information such as route parameters, static data, resolve data, global query params, and the global fragment.
</td>
</tr>
<tr>
<td>
<code>RouterState</code>
</td>
<td>
The current state of the router including a tree of the currently activated routes together with convenience methods for traversing the route tree.
</td>
</tr>
<tr>
<td>
<b><i>Link parameters array</i></b>
</td>
<td>
An array that the router interprets as a routing instruction.
You can bind that array to a <code>RouterLink</code> or pass the array as an argument to the <code>Router.navigate</code> method.
</td>
</tr>
<tr>
<td>
<b><i>Routing component</i></b>
</td>
<td>
An Angular component with a <code>RouterOutlet</code> that displays views based on router navigations.