{ "id": "guide/router-tutorial", "title": "Using Angular routes in a single-page application", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Using Angular routes in a single-page applicationlink

\n

This tutorial describes how you can build a single-page application, SPA that uses multiple Angular routes.

\n

In a Single Page Application (SPA), all of your application's functions exist in a single HTML page.\nAs users access your application's features, the browser needs to render only the parts that matter to the user, instead of loading a new page. This pattern can significantly improve your application's user experience.

\n

To define how users navigate through your application, you use routes. You can add routes to define how users navigate from one part of your application to another.\nYou can also configure routes to guard against unexpected or unauthorized behavior.

\n

To explore a sample app featuring the contents of this tutorial, see the .

\n

Objectiveslink

\n\n

Prerequisiteslink

\n

To complete this tutorial, you should have a basic understanding of the following concepts:

\n\n

You might find the Tour of Heroes tutorial helpful, but it is not required.

\n

Create a sample applicationlink

\n

Using the Angular CLI, create a new application, angular-router-sample. This application will have two components: crisis-list and heroes-list.

\n
    \n
  1. \n

    Create a new Angular project, angular-router-sample.

    \n\nng new angular-router-sample\n\n

    When prompted with Would you like to add Angular routing?, select N.

    \n

    When prompted with Which stylesheet format would you like to use?, select CSS.

    \n

    After a few moments, a new project, angular-router-sample, is ready.

    \n
  2. \n
  3. \n

    From your terminal, navigate to the angular-router-sample directory.

    \n
  4. \n
  5. \n

    Create a component, crisis-list.

    \n\n ng generate component crisis-list\n\n
  6. \n
  7. \n

    In your code editor, locate the file, crisis-list.component.html and replace\nthe placeholder content with the following HTML.

    \n\n<h3>CRISIS CENTER</h3>\n<p>Get your crisis here</p>\n\n\n\n
  8. \n
  9. \n

    Create a second component, heroes-list.

    \n\n ng generate component heroes-list\n\n
  10. \n
  11. \n

    In your code editor, locate the file, heroes-list.component.html and replace the placeholder content with the following HTML.

    \n\n<h3>HEROES</h3>\n<p>Get your heroes here</p>\n\n\n\n
  12. \n
  13. \n

    In your code editor, open the file, app.component.html and replace its contents with the following HTML.

    \n\n<h1>Angular Router Sample</h1>\n<app-crisis-list></app-crisis-list>\n<app-heroes-list></app-heroes-list>\n\n\n
  14. \n
  15. \n

    Verify that your new application runs as expected by running the ng serve command.

    \n\n ng serve\n\n
  16. \n
  17. \n

    Open a browser to http://localhost:4200.

    \n

    You should see a single web page, consisting of a title and the HTML of your two components.

    \n
  18. \n
\n

Import RouterModule from @angular/routerlink

\n

Routing allows you to display specific views of your application depending on the URL path.\nTo add this functionality to your sample application, you need to update the app.module.ts file to use the module, RouterModule.\nYou import this module from @angular/router.

\n
    \n
  1. \n

    From your code editor, open the app.module.ts file.

    \n
  2. \n
  3. \n

    Add the following import statement.

    \n\nimport { RouterModule } from '@angular/router';\n\n\n
  4. \n
\n

Define your routeslink

\n

In this section, you'll define two routes:

\n\n

A route definition is a JavaScript object. Each route typically has two properties. The first property, path, is a string\nthat specifies the URL path for the route. The second property, component, is a string that specifies\nwhat component your application should display for that path.

\n
    \n
  1. \n

    From your code editor, open the app.module.ts file.

    \n
  2. \n
  3. \n

    Locate the @NgModule() section.

    \n
  4. \n
  5. \n

    Replace the imports array in that section with the following.

    \n\nimports: [\n BrowserModule,\n RouterModule.forRoot([\n {path: 'crisis-list', component: CrisisListComponent},\n {path: 'heroes-list', component: HeroesListComponent},\n ]),\n],\n\n\n
  6. \n
\n

This code adds the RouterModule to the imports array. Next, the code uses the forRoot() method of the RouterModule to\ndefine your two routes. This method takes an array of JavaScript objects, with each object defining the proprties of a route.\nThe forRoot() method ensures that your application only instantiates one RouterModule. For more information, see\nSingleton Services.

\n

Update your component with router-outletlink

\n

At this point, you have defined two routes for your application. However, your application\nstill has both the crisis-list and heroes-list components hard-coded in your app.component.html template. For your routes to\nwork, you need to update your template to dynamically load a component based on the URL path.

\n

To implement this functionality, you add the router-outlet directive to your template file.

\n
    \n
  1. \n

    From your code editor, open the app.component.html file.

    \n
  2. \n
  3. \n

    Delete the following lines.

    \n\n<app-crisis-list></app-crisis-list>\n<app-heroes-list></app-heroes-list>\n\n\n
  4. \n
  5. \n

    Add the router-outlet directive.

    \n\n<router-outlet></router-outlet>\n\n\n
  6. \n
\n

View your updated application in your browser. You should see only the application title. To\nview the crisis-list component, add crisis-list to the end of the path in your browser's\naddress bar. For example:

\n\nhttp://localhost:4200/crisis-list\n\n

Notice that the crisis-list component displays. Angular is using the route you defined to dynamically load the\ncomponent. You can load the heroes-list component the same way:

\n\nhttp://localhost:4200/heroes-list\n\n

Control navigation with UI elementslink

\n

Currently, your application supports two routes. However, the only way to use those routes\nis for the user to manually type the path in the browser's address bar. In this section, you'll\nadd two links that users can click to navigate between the heroes-list and crisis-list\ncomponents. You'll also add some CSS styles. While these styles are not required, they make\nit easier to identify the link for the currently-displayed component. You'll add that functionality\nin the next section.

\n
    \n
  1. \n

    Open the app.component.html file and add the following HTML below the title.

    \n\n<nav>\n <a class=\"button\" routerLink=\"/crisis-list\">Crisis Center</a> |\n <a class=\"button\" routerLink=\"/heroes-list\">Heroes</a>\n</nav>\n\n\n

    This HTML uses an Angular directive, routerLink. This directive connects the routes\nyou defined to your template files.

    \n
  2. \n
  3. \n

    Open the app.component.css file and add the following styles.

    \n\n.button {\n box-shadow: inset 0 1px 0 0 #ffffff;\n background: #ffffff linear-gradient(to bottom, #ffffff 5%, #f6f6f6 100%);\n border-radius: 6px;\n border: 1px solid #dcdcdc;\n display: inline-block;\n cursor: pointer;\n color: #666666;\n font-family: Arial, sans-serif;\n font-size: 15px;\n font-weight: bold;\n padding: 6px 24px;\n text-decoration: none;\n text-shadow: 0 1px 0 #ffffff;\n outline: 0;\n}\n.activebutton {\n box-shadow: inset 0 1px 0 0 #dcecfb;\n background: #bddbfa linear-gradient(to bottom, #bddbfa 5%, #80b5ea 100%);\n border-radius: 6px;\n border: 1px solid #84bbf3;\n display: inline-block;\n cursor: pointer;\n color: #ffffff;\n font-family: Arial, sans-serif;\n font-size: 15px;\n font-weight: bold;\n padding: 6px 24px;\n text-decoration: none;\n text-shadow: 0 1px 0 #528ecc;\n outline: 0;\n}\n\n\n\n
  4. \n
\n

If you view your application in the browser, you should see these two links. When you click\non a link, the corresponding component appears.

\n

Identify the active routelink

\n

While users can navigate your application using the links you added in the previous section,\nthey don't have an easy way to identify what the active route is. You can add this functionality\nusing Angular's routerLinkActive directive.

\n
    \n
  1. \n

    From your code editor, open the app.component.html file.

    \n
  2. \n
  3. \n

    Update the anchor tags to include the routerLinkActive directive.

    \n\n<nav>\n <a class=\"button\" routerLink=\"/crisis-list\" routerLinkActive=\"activebutton\">Crisis Center</a> |\n <a class=\"button\" routerLink=\"/heroes-list\" routerLinkActive=\"activebutton\">Heroes</a>\n</nav>\n\n\n
  4. \n
\n

View your application again. As you click one of the buttons, the style for that button updates\nautomatically, identifying the active component to the user. By adding the routerLinkActive\ndirective, you inform your application to apply a specific CSS class to the active route. In this\ntutorial, that CSS class is activebutton, but you could use any class that you want.

\n

Adding a redirectlink

\n

In this step of the tutorial, you add a route that redirects the user to display the /heroes-list component.

\n
    \n
  1. \n

    From your code editor, open the app.module.ts file.

    \n
  2. \n
  3. \n

    In the imports array, update the RouterModule section as follows.

    \n\nimports: [\n BrowserModule,\n RouterModule.forRoot([\n {path: 'crisis-list', component: CrisisListComponent},\n {path: 'heroes-list', component: HeroesListComponent},\n {path: '', redirectTo: '/heroes-list', pathMatch: 'full'},\n ]),\n],\n\n\n

    Notice that this new route uses an empty string as its path. In addition, it replaces the component property with two new ones:

    \n
      \n
    • redirectTo. This property instructs Angular to redirect from an empty path to the\nheroes-list path.
    • \n
    • pathMatch. This property instructs Angular on how much of the URL to match. For this\ntutorial, you should set this property to full. This strategy is recommended when\nyou have an empty string for a path. For more information about this property,\nsee the Route API documentation.
    • \n
    \n
  4. \n
\n

Now when you open your application, it displays the heroes-list component by default.

\n

Adding a 404 pagelink

\n

It is possible for a user to try to access a route that you have not defined. To account for\nthis behavior, the best practice is to display a 404 page. In this section, you'll create a 404 page and\nupdate your route configuration to show that page for any unspecified routes.

\n
    \n
  1. \n

    From the terminal, create a new component, PageNotFound.

    \n\nng generate component page-not-found\n\n
  2. \n
  3. \n

    From your code editor, open the page-not-found.component.html file and replace its contents\nwith the following HTML.

    \n\n<h2>Page Not Found</h2>\n<p>We couldn't find that page! Not even with x-ray vision.</p>\n\n\n\n
  4. \n
  5. \n

    Open the app.module.ts file. In the imports array, update the RouterModule section as follows.

    \n\nimports: [\n BrowserModule,\n RouterModule.forRoot([\n {path: 'crisis-list', component: CrisisListComponent},\n {path: 'heroes-list', component: HeroesListComponent},\n {path: '', redirectTo: '/heroes-list', pathMatch: 'full'},\n {path: '**', component: PageNotFoundComponent}\n ]),\n],\n\n\n

    The new route uses a path, **. This path is how Angular identifies a wildcard route. Any route\nthat does not match an existing route in your configuration will use this route.

    \n
    \n Notice that the wildcard route is placed at the end of the array. The order of your\n routes is important, as Angular applies routes in order and uses the first match it finds.\n
    \n
  6. \n
\n

Try navigating to a non-existing route on your application, such as http://localhost:4200/powers.\nThis route doesn't match anything defined in your app.module.ts file. However, because you\ndefined a wildcard route, the application automatically displays your PageNotFound component.

\n

Next stepslink

\n

At this point, you have a basic application that uses Angular's routing feature to change\nwhat components the user can see based on the URL address. You have extended these features\nto include a redirect, as well as a wildcard route to display a custom 404 page.

\n

For more information about routing, see the following topics:

\n\n\n \n
\n\n\n" }