{ "id": "guide/router", "title": "In-app navigation: routing to views", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

In-app navigation: routing to viewslink

\n

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.\nAs users perform application tasks, they need to move between the different views that you have defined.

\n

To handle the navigation from one view to the next, you use the Angular Router.\nThe Router enables navigation by interpreting a browser URL as an instruction to change the view.

\n

To explore a sample app featuring the router's primary features, see the .

\n

Prerequisiteslink

\n

Before creating a route, you should be familiar with the following:

\n\n

For an introduction to Angular with a ready-made app, see Getting Started.\nFor a more in-depth experience of building an Angular app, see the Tour of Heroes tutorial. Both guide you through using component classes and templates.

\n\n

Generate an app with routing enabledlink

\n

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.\nThe app name in the following example is routing-app.

\n\n ng new routing-app --routing\n\n

When generating a new app, the CLI prompts you to select CSS or a CSS preprocessor.\nFor this example, accept the default of CSS.

\n

Adding components for routinglink

\n

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:

\n\n ng generate component first\n\n

Repeat this step for a second component but give it a different name.\nHere, the new name is second.

\n\n ng generate component second\n\n

The CLI automatically appends Component, so if you were to write first-component, your component would be FirstComponentComponent.

\n\n
\n

<base href>link

\n

This guide works with a CLI-generated Angular app.\nIf you are working manually, make sure that you have <base href=\"/\"> in the <head> of your index.html file.\nThis assumes that the app folder is the application root, and uses \"/\".

\n \n
\n

Importing your new componentslink

\n

To use your new components, import them into AppRoutingModule at the top of the file, as follows:

\n\n\nimport { FirstComponent } from './first/first.component';\nimport { SecondComponent } from './second/second.component';\n\n\n\n

Defining a basic routelink

\n

There are three fundamental building blocks to creating a route.

\n

Import the AppRoutingModule into AppModule and add it to the imports array.

\n

The Angular CLI performs this step for you.\nHowever, if you are creating an app manually or working with an existing, non-CLI app, verify that the imports and configuration are correct.\nThe following is the default AppModule using the CLI with the --routing flag.

\n \nimport { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppRoutingModule } from './app-routing.module'; // CLI imports AppRoutingModule\nimport { AppComponent } from './app.component';\n\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n AppRoutingModule // CLI adds AppRoutingModule to the AppModule's imports array\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }\n\n\n\n
    \n
  1. \n

    Import RouterModule and Routes into your routing module.

    \n

    The Angular CLI performs this step automatically.\nThe CLI also sets up a Routes array for your routes and configures the imports and exports arrays for @NgModule().

    \n\nimport { NgModule } from '@angular/core';\nimport { Routes, RouterModule } from '@angular/router'; // CLI imports router\n\nconst routes: Routes = []; // sets up routes constant where you define your routes\n\n// configures NgModule imports and exports\n@NgModule({\n imports: [RouterModule.forRoot(routes)],\n exports: [RouterModule]\n})\nexport class AppRoutingModule { }\n\n\n\n
  2. \n
  3. \n

    Define your routes in your Routes array.

    \n

    Each route in this array is a JavaScript object that contains two properties.\nThe first property, path, defines the URL path for the route.\nThe second property, component, defines the component Angular should use for the corresponding path.

    \n\nconst routes: Routes = [\n { path: 'first-component', component: FirstComponent },\n { path: 'second-component', component: SecondComponent },\n];\n\n\n
  4. \n
  5. \n

    Add your routes to your application.

    \n

    Now that you have defined your routes, you can add them to your application.\nFirst, add links to the two components.\nAssign the anchor tag that you want to add the route to the routerLink attribute.\nSet the value of the attribute to the component to show when a user clicks on each link.\nNext, update your component template to include <router-outlet>.\nThis element informs Angular to update the application view with the component for the selected route.

    \n\n<h1>Angular Router App</h1>\n<!-- This nav gives you links to click, which tells the router which route to use (defined in the routes constant in AppRoutingModule) -->\n<nav>\n <ul>\n <li><a routerLink=\"/first-component\" routerLinkActive=\"active\">First Component</a></li>\n <li><a routerLink=\"/second-component\" routerLinkActive=\"active\">Second Component</a></li>\n </ul>\n</nav>\n<!-- The routed views render in the <router-outlet>-->\n<router-outlet></router-outlet>\n\n\n\n
  6. \n
\n\n

Route orderlink

\n

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.\nList routes with a static path first, followed by an empty path route, which matches the default route.\nThe wildcard route comes last because it matches every URL and the Router selects it only if no other routes match first.

\n\n

Getting route informationlink

\n

Often, as a user navigates your application, you want to pass information from one component to another.\nFor example, consider an application that displays a shopping list of grocery items.\nEach item in the list has a unique id.\nTo edit an item, users click an Edit button, which opens an EditGroceryItem component.\nYou want that component to retrieve the id for the grocery item so it can display the right information to the user.

\n

You can use a route to pass this type of information to your application components.\nTo do so, you use the ActivatedRoute interface.

\n

To get information from a route:

\n
    \n
  1. \n

    Import ActivatedRoute and ParamMap to your component.

    \n\nimport { Router, ActivatedRoute, ParamMap } from '@angular/router';\n\n\n

    These import statements add several important elements that your component needs.\nTo learn more about each, see the following API pages:

    \n\n
  2. \n
  3. \n

    Inject an instance of ActivatedRoute by adding it to your application's constructor:

    \n\nconstructor(\n private route: ActivatedRoute,\n) {}\n\n\n
  4. \n
  5. \n

    Update the ngOnInit() method to access the ActivatedRoute and track the id parameter:

    \n \n ngOnInit() {\n this.route.queryParams.subscribe(params => {\n this.name = params['name'];\n });\n }\n \n

    Note: The preceding example uses a variable, name, and assigns it the value based on the name parameter.

    \n
  6. \n
\n\n

Setting up wildcard routeslink

\n

A well-functioning application should gracefully handle when users attempt to navigate to a part of your application that does not exist.\nTo add this functionality to your application, you set up a wildcard route.\nThe Angular router selects this route any time the requested URL doesn't match any router paths.

\n

To set up a wildcard route, add the following code to your routes definition.

\n\n\n{ path: '**', component: }\n\n\n

The two asterisks, **, indicate to Angular that this routes definition is a wildcard route.\nFor the component property, you can define any component in your application.\nCommon choices include an application-specific PageNotFoundComponent, which you can define to display a 404 page to your users; or a redirect to your application's main component.\nA wildcard route is the last route because it matches any URL.\nFor more detail on why order matters for routes, see Route order.

\n\n

Displaying a 404 pagelink

\n

To display a 404 page, set up a wildcard route with the component property set to the component you'd like to use for your 404 page as follows:

\n\nconst routes: Routes = [\n { path: 'first-component', component: FirstComponent },\n { path: 'second-component', component: SecondComponent },\n { path: '**', component: PageNotFoundComponent }, // Wildcard route for a 404 page\n];\n\n\n

The last route with the path of ** is a wildcard route.\nThe 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.

\n

Setting up redirectslink

\n

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.

\n\nconst routes: Routes = [\n { path: 'first-component', component: FirstComponent },\n { path: 'second-component', component: SecondComponent },\n { path: '', redirectTo: '/first-component', pathMatch: 'full' }, // redirect to `first-component`\n { path: '**', component: PageNotFoundComponent }, // Wildcard route for a 404 page\n];\n\n\n

In this example, the third route is a redirect so that the router defaults to the first-component route.\nNotice that this redirect precedes the wildcard route.\nHere, path: '' means to use the initial relative URL ('').

\n

For more details on pathMatch see Spotlight on pathMatch.

\n\n

Nesting routeslink

\n

As your application grows more complex, you may want to create routes that are relative to a component other than your root component.\nThese types of nested routes are called child routes.\nThis means you're adding a second <router-outlet> to your app, because it is in addition to the <router-outlet> in AppComponent.

\n

In this example, there are two additional child components, child-a, and child-b.\nHere, FirstComponent has its own <nav> and a second <router-outlet> in addition to the one in AppComponent.

\n\n<h2>First Component</h2>\n\n<nav>\n <ul>\n <li><a routerLink=\"child-a\">Child A</a></li>\n <li><a routerLink=\"child-b\">Child B</a></li>\n </ul>\n</nav>\n\n<router-outlet></router-outlet>\n\n\n

A child route is like any other route, in that it needs both a path and a component.\nThe one difference is that you place child routes in a children array within the parent route.

\n\nconst routes: Routes = [\n {\n path: 'first-component',\n component: FirstComponent, // this is the component with the <router-outlet> in the template\n children: [\n {\n path: 'child-a', // child route path\n component: ChildAComponent, // child route component that the router renders\n },\n {\n path: 'child-b',\n component: ChildBComponent, // another child route component that the router renders\n },\n ],\n },\n];\n\n\n\n

Using relative pathslink

\n

Relative paths allow you to define paths that are relative to the current URL segment.\nThe following example shows a relative route to another component, second-component.\nFirstComponent 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.\nRather than writing out the whole path to get to SecondComponent, you can use the ../ notation to go up a level.

\n\n\n<h2>First Component</h2>\n\n<nav>\n <ul>\n <li><a routerLink=\"../second-component\">Relative Route to second component</a></li>\n </ul>\n</nav>\n<router-outlet></router-outlet>\n\n\n\n

In addition to ../, you can use ./ or no leading slash to specify the current level.

\n

Specifying a relative routelink

\n

To specify a relative route, use the NavigationExtras relativeTo property.\nIn the component class, import NavigationExtras from the @angular/router.

\n

Then use relativeTo in your navigation method.\nAfter the link parameters array, which here contains items, add an object with the relativeTo property set to the ActivatedRoute, which is this.route.

\n\ngoToItems() {\n this.router.navigate(['items'], { relativeTo: this.route });\n}\n\n\n

The goToItems() method interprets the destination URI as relative to the activated route and navigates to the items route.

\n

Accessing query parameters and fragmentslink

\n

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.

\n

First, import the following members in the component you want to navigate from.

\n\n\nimport { ActivatedRoute } from '@angular/router';\nimport { Observable } from 'rxjs';\nimport { switchMap } from 'rxjs/operators';\n\n\n

Next inject the activated route service:

\n\nconstructor(private route: ActivatedRoute) {}\n\n

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.\nThis 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.

\n\nheroes$: Observable;\nselectedId: number;\nheroes = HEROES;\n\nngOnInit() {\n this.heroes$ = this.route.paramMap.pipe(\n switchMap(params => {\n this.selectedId = Number(params.get('id'));\n return this.service.getHeroes();\n })\n );\n}\n\n\n

Next, in the component that you want to navigate to, import the following members.

\n\n\nimport { Router, ActivatedRoute, ParamMap } from '@angular/router';\nimport { Observable } from 'rxjs';\n\n\n

Inject ActivatedRoute and Router in the constructor of the component class so they are available to this component:

\n\n\n hero$: Observable;\n\n constructor(\n private route: ActivatedRoute,\n private router: Router ) {}\n\n ngOnInit() {\n const heroId = this.route.snapshot.paramMap.get('id');\n this.hero$ = this.service.getHero(heroId);\n }\n\n gotoItems(hero: Hero) {\n const heroId = hero ? hero.id : null;\n // Pass along the hero id if available\n // so that the HeroList component can select that item.\n this.router.navigate(['/heroes', { id: heroId }]);\n }\n\n\n\n

Lazy loadinglink

\n

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.\nAdditionally, you can preload parts of your app in the background to improve the user experience.

\n

For more information on lazy loading and preloading see the dedicated guide Lazy loading NgModules.

\n

Preventing unauthorized accesslink

\n

Use route guards to prevent users from navigating to parts of an app without authorization.\nThe following route guards are available in Angular:

\n\n

To use route guards, consider using component-less routes as this facilitates guarding child routes.

\n

Create a service for your guard:

\n\n ng generate guard your-guard\n\n

In your guard class, implement the guard you want to use.\nThe following example uses CanActivate to guard the route.

\n\nexport class YourGuard implements CanActivate {\n canActivate(\n next: ActivatedRouteSnapshot,\n state: RouterStateSnapshot): boolean {\n // your logic goes here\n }\n}\n\n

In your routing module, use the appropriate property in your routes configuration.\nHere, canActivate tells the router to mediate navigation to this particular route.

\n\n{\n path: '/your-path',\n component: YourComponent,\n canActivate: [YourGuard],\n}\n\n

For more information with a working example, see the routing tutorial section on route guards.

\n\n

A link parameters array holds the following ingredients for router navigation:

\n\n

You can bind the RouterLink directive to such an array like this:

\n\n<a [routerLink]=\"['/heroes']\">Heroes</a>\n\n\n

The following is a two-element array when specifying a route parameter:

\n\n<a [routerLink]=\"['/hero', hero.id]\">\n <span class=\"badge\">{{ hero.id }}</span>{{ hero.name }}\n</a>\n\n\n

You can provide optional route parameters in an object, as in { foo: 'foo' }:

\n\n<a [routerLink]=\"['/crisis-center', { foo: 'foo' }]\">Crisis Center</a>\n\n\n

These three examples cover the needs of an app with one level of routing.\nHowever, with a child router, such as in the crisis center, you create new link array possibilities.

\n

The following minimal RouterLink example builds upon a specified default child route for the crisis center.

\n\n<a [routerLink]=\"['/crisis-center']\">Crisis Center</a>\n\n\n

Note the following:

\n\n

Consider the following router link that navigates from the root of the application down to the Dragon Crisis:

\n\n<a [routerLink]=\"['/crisis-center', 1]\">Dragon Crisis</a>\n\n\n\n

You could also redefine the AppComponent template with Crisis Center routes exclusively:

\n\ntemplate: `\n <h1 class=\"title\">Angular Router</h1>\n <nav>\n <a [routerLink]=\"['/crisis-center']\">Crisis Center</a>\n <a [routerLink]=\"['/crisis-center/1', { foo: 'foo' }]\">Dragon Crisis</a>\n <a [routerLink]=\"['/crisis-center/2']\">Shark Crisis</a>\n </nav>\n <router-outlet></router-outlet>\n`\n\n\n

In summary, you can write applications with one, two or more levels of routing.\nThe 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.

\n\n\n

LocationStrategy and browser URL styleslink

\n

When the router navigates to a new component view, it updates the browser's location and history with a URL for that view.\nAs this is a strictly local URL the browser won't send this URL to the server and will not reload the page.

\n

Modern HTML5 browsers support history.pushState, a technique that changes a browser's location and history without triggering a server page request.\nThe router can compose a \"natural\" URL that is indistinguishable from one that would otherwise require a page load.

\n

Here's the Crisis Center URL in this \"HTML5 pushState\" style:

\n\n localhost:3002/crisis-center/\n\n\n

Older browsers send page requests to the server when the location URL changes unless the change occurs after a \"#\" (called the \"hash\").\nRouters can take advantage of this exception by composing in-application route URLs with hashes.\nHere's a \"hash URL\" that routes to the Crisis Center.

\n\n localhost:3002/src/#/crisis-center/\n\n\n

The router supports both styles with two LocationStrategy providers:

\n
    \n
  1. PathLocationStrategy—the default \"HTML5 pushState\" style.
  2. \n
  3. HashLocationStrategy—the \"hash URL\" style.
  4. \n
\n

The RouterModule.forRoot() function sets the LocationStrategy to the PathLocationStrategy, which makes it the default strategy.\nYou also have the option of switching to the HashLocationStrategy with an override during the bootstrapping process.

\n
\n

For more information on providers and the bootstrap process, see Dependency Injection.

\n
\n

Choosing a routing strategylink

\n

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.

\n

Almost all Angular projects should use the default HTML5 style.\nIt produces URLs that are easier for users to understand and it preserves the option to do server-side rendering.

\n

Rendering critical pages on the server is a technique that can greatly improve perceived responsiveness when the app first loads.\nAn 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.

\n

This option is only available if application URLs look like normal web URLs without hashes (#) in the middle.

\n

<base href>link

\n

The router uses the browser's history.pushState for navigation.\npushState allows you to customize in-app URL paths; for example, localhost:4200/crisis-center.\nThe in-app URLs can be indistinguishable from server URLs.

\n

Modern HTML5 browsers were the first to support pushState which is why many people refer to these URLs as \"HTML5 style\" URLs.

\n
\n

HTML5 style navigation is the router default.\nIn the LocationStrategy and 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.

\n
\n

You must add a <base href> element to the app's index.html for pushState routing to work.\nThe browser uses the <base href> value to prefix relative URLs when referencing CSS files, scripts, and images.

\n

Add the <base> element just after the <head> tag.\nIf the app folder is the application root, as it is for this application,\nset the href value in index.html as shown here.

\n\n<base href=\"/\">\n\n\n

HTML5 URLs and the <base href>link

\n

The guidelines that follow will refer to different parts of a URL. This diagram outlines what those parts refer to:

\n\nfoo://example.com:8042/over/there?name=ferret#nose\n\\_/ \\______________/\\_________/ \\_________/ \\__/\n | | | | |\nscheme authority path query fragment\n\n

While the router uses the HTML5 pushState style by default, you must configure that strategy with a <base href>.

\n

The preferred way to configure the strategy is to add a <base href> element tag in the <head> of the index.html.

\n\n<base href=\"/\">\n\n\n

Without that tag, the browser may not be able to load resources\n(images, CSS, scripts) when \"deep linking\" into the app.

\n

Some developers may not be able to add the <base> element, perhaps because they don't have access to <head> or the index.html.

\n

Those developers may still use HTML5 URLs by taking the following two steps:

\n
    \n
  1. Provide the router with an appropriate APP_BASE_HREF value.
  2. \n
  3. Use root URLs (URLs with an authority) for all web resources: CSS, images, scripts, and template HTML files.
  4. \n
\n\n

For more complete information on how <base href> is used to construct target URIs, see the RFC section on transforming references.

\n\n

HashLocationStrategylink

\n

You can use HashLocationStrategy by providing the useHash: true in an object as the second argument of the RouterModule.forRoot() in the AppModule.

\n\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { FormsModule } from '@angular/forms';\nimport { Routes, RouterModule } from '@angular/router';\n\nimport { AppComponent } from './app.component';\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\n\nconst routes: Routes = [\n\n];\n\n@NgModule({\n imports: [\n BrowserModule,\n FormsModule,\n RouterModule.forRoot(routes, { useHash: true }) // .../#/crisis-center/\n ],\n declarations: [\n AppComponent,\n PageNotFoundComponent\n ],\n providers: [\n\n ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }\n\n\n\n

Router Referencelink

\n

The following sections highlight some core router concepts.

\n\n

Router importslink

\n

The Angular Router is an optional service that presents a particular component view for a given URL.\nIt is not part of the Angular core and thus is in its own library package, @angular/router.

\n

Import what you need from it as you would from any other Angular package.

\n\nimport { RouterModule, Routes } from '@angular/router';\n\n\n
\n

For more on browser URL styles, see LocationStrategy and browser URL styles.

\n
\n\n

Configurationlink

\n

A routed Angular application has one singleton instance of the Router service.\nWhen the browser's URL changes, that router looks for a corresponding Route from which it can determine the component to display.

\n

A router has no routes until you configure it.\nThe following example creates five route definitions, configures the router via the RouterModule.forRoot() method, and adds the result to the AppModule's imports array.

\n\nconst appRoutes: Routes = [\n { path: 'crisis-center', component: CrisisListComponent },\n { path: 'hero/:id', component: HeroDetailComponent },\n {\n path: 'heroes',\n component: HeroListComponent,\n data: { title: 'Heroes List' }\n },\n { path: '',\n redirectTo: '/heroes',\n pathMatch: 'full'\n },\n { path: '**', component: PageNotFoundComponent }\n];\n\n@NgModule({\n imports: [\n RouterModule.forRoot(\n appRoutes,\n { enableTracing: true } // <-- debugging purposes only\n )\n // other imports here\n ],\n ...\n})\nexport class AppModule { }\n\n\n\n

The appRoutes array of routes describes how to navigate.\nPass it to the RouterModule.forRoot() method in the module imports to configure the router.

\n

Each Route maps a URL path to a component.\nThere are no leading slashes in the path.\nThe router parses and builds the final URL for you, which allows you to use both relative and absolute paths when navigating between application views.

\n

The :id in the second route is a token for a route parameter.\nIn a URL such as /hero/42, \"42\" is the value of the id parameter.\nThe corresponding HeroDetailComponent uses that value to find and present the hero whose id is 42.

\n

The data property in the third route is a place to store arbitrary data associated with\nthis specific route.\nThe 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.\nYou can use the resolve guard to retrieve dynamic data.

\n

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.\nThis default route redirects to the route for the /heroes URL and, therefore, displays the HeroesListComponent.

\n

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.\nThis outputs each router event that took place during each navigation lifecycle to the browser console.\nUse enableTracing only for debugging purposes.\nYou set the enableTracing: true option in the object passed as the second argument to the RouterModule.forRoot() method.

\n\n

Router outletlink

\n

The RouterOutlet is a directive from the router library that is used like a component.\nIt acts as a placeholder that marks the spot in the template where the router should\ndisplay the components for that outlet.

\n\n <router-outlet></router-outlet>\n <!-- Routed components go here -->\n\n\n

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.

\n\n\n

Router linkslink

\n

To navigate as a result of some user action such as the click of an anchor tag, use RouterLink.

\n

Consider the following template:

\n\n<h1>Angular Router</h1>\n<nav>\n <a routerLink=\"/crisis-center\" routerLinkActive=\"active\">Crisis Center</a>\n <a routerLink=\"/heroes\" routerLinkActive=\"active\">Heroes</a>\n</nav>\n<router-outlet></router-outlet>\n\n\n

The RouterLink directives on the anchor tags give the router control over those elements.\nThe navigation paths are fixed, so you can assign a string to the routerLink (a \"one-time\" binding).

\n

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.\nThe router resolves that array into a complete URL.

\n\n

Active router linkslink

\n

The RouterLinkActive directive toggles CSS classes for active RouterLink bindings based on the current RouterState.

\n

On each anchor tag, you see a property binding to the RouterLinkActive directive that looks like routerLinkActive=\"...\".

\n

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).\nYou 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.

\n

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.\nTo 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.

\n\n

Router statelink

\n

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.

\n

Each ActivatedRoute in the RouterState provides methods to traverse up and down the route tree to get information from parent, child and sibling routes.

\n\n

Activated routelink

\n

The route path and parameters are available through an injected router service called the ActivatedRoute.\nIt has a great deal of useful information including:

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Property\n \n Description\n
\n url\n \n

An Observable of the route path(s), represented as an array of strings for each part of the route path.

\n
\n data\n \n

An Observable that contains the data object provided for the route.\nAlso contains any resolved values from the resolve guard.

\n
\n paramMap\n \n

An Observable that contains a map of the required and optional parameters specific to the route.\nThe map supports retrieving single and multiple values from the same parameter.

\n
\n queryParamMap\n \n

An Observable that contains a map of the query parameters available to all routes.\nThe map supports retrieving single and multiple values from the query parameter.

\n
\n fragment\n \n

An Observable of the URL fragment available to all routes.

\n
\n outlet\n \n

The name of the RouterOutlet used to render the route.\nFor an unnamed outlet, the outlet name is primary.

\n
\n routeConfig\n \n

The route configuration used for the route that contains the origin path.

\n
\n parent\n \n

The route's parent ActivatedRoute when this route is a child route.

\n
\n firstChild\n \n

Contains the first ActivatedRoute in the list of this route's child routes.

\n
\n children\n \n

Contains all the child routes activated under the current route.

\n
\n
\n

Two older properties are still available, however, their replacements are preferable as they may be deprecated in a future Angular version.

\n\n
\n

Router eventslink

\n

During each navigation, the Router emits navigation events through the Router.events property.\nThese 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.

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Router Event\n \n Description\n
\n NavigationStart\n \n

An event triggered when navigation starts.

\n
\n RouteConfigLoadStart\n \n

An event triggered before the Router\nlazy loads a route configuration.

\n
\n RouteConfigLoadEnd\n \n

An event triggered after a route has been lazy loaded.

\n
\n RoutesRecognized\n \n

An event triggered when the Router parses the URL and the routes are recognized.

\n
\n GuardsCheckStart\n \n

An event triggered when the Router begins the Guards phase of routing.

\n
\n ChildActivationStart\n \n

An event triggered when the Router begins activating a route's children.

\n
\n ActivationStart\n \n

An event triggered when the Router begins activating a route.

\n
\n GuardsCheckEnd\n \n

An event triggered when the Router finishes the Guards phase of routing successfully.

\n
\n ResolveStart\n \n

An event triggered when the Router begins the Resolve phase of routing.

\n
\n ResolveEnd\n \n

An event triggered when the Router finishes the Resolve phase of routing successfuly.

\n
\n ChildActivationEnd\n \n

An event triggered when the Router finishes activating a route's children.

\n
\n ActivationEnd\n \n

An event triggered when the Router finishes activating a route.

\n
\n NavigationEnd\n \n

An event triggered when navigation ends successfully.

\n
\n NavigationCancel\n \n

An event triggered when navigation is canceled.\nThis can happen when a Route Guard returns false during navigation,\nor redirects by returning a UrlTree.

\n
\n NavigationError\n \n

An event triggered when navigation fails due to an unexpected error.

\n
\n Scroll\n \n

An event that represents a scrolling event.

\n
\n

When you enable the enableTracing option, Angular logs these events to the console.\nFor an example of filtering router navigation events, see the router section of the Observables in Angular guide.

\n

Router terminologylink

\n

Here are the key Router terms and their meanings:

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Router Part\n \n Meaning\n
\n Router\n \n Displays the application component for the active URL.\n Manages navigation from one component to the next.\n
\n RouterModule\n \n A separate NgModule that provides the necessary service providers\n and directives for navigating through application views.\n
\n Routes\n \n Defines an array of Routes, each mapping a URL path to a component.\n
\n Route\n \n Defines how the router should navigate to a component based on a URL pattern.\n Most routes consist of a path and a component type.\n
\n RouterOutlet\n \n The directive (<router-outlet>) that marks where the router displays a view.\n
\n RouterLink\n \n The directive for binding a clickable HTML element to a route. Clicking an element with a routerLink directive that is bound to a string or a link parameters array triggers a navigation.\n
\n RouterLinkActive\n \n The directive for adding/removing classes from an HTML element when an associated routerLink contained on or inside the element becomes active/inactive.\n
\n ActivatedRoute\n \n 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.\n
\n RouterState\n \n The current state of the router including a tree of the currently activated routes together with convenience methods for traversing the route tree.\n
\n Link parameters array\n \n An array that the router interprets as a routing instruction.\n You can bind that array to a RouterLink or pass the array as an argument to the Router.navigate method.\n
\n Routing component\n \n An Angular component with a RouterOutlet that displays views based on router navigations.\n
\n\n \n
\n\n\n" }