Routing and Navigation in Angular

Angular

Introduction to Angular – Angular is a development platform, built on TypeScript. As a platform, Angular includes – a component-based framework for building scalable web applications a collection of well-integrated libraries that cover a wide variety of features, including routing, forms management, client-server communication, and more a suite of developer tools to help you develop, build, test, and update your code. Here we will learn the routing and navigation in angular for our angular applications.

Create a sample application for routing and navigation in angular

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

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

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

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

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

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

3. Create a component, crisis-list.

ng generate component crisis-list

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

<h3>CRISIS CENTER</h3>
<p>Get your crisis here</p>

5. Create a second component, heroes-list.

ng generate component heroes-list

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

<h3>HEROES</h3>
<p>Get your heroes here</p>

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

<h1>Angular Router Sample</h1>
<app-crisis-list></app-crisis-list>
<app-heroes-list></app-heroes-list>

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

ng serve

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

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

Angular : Import RouterModule from @angular/router

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

  1. From your code editor, open the app.module.ts file.
  2. Add the following import statement in src/app/app.module.ts
import { RouterModule } from '@angular/router';

Define your routes in Angular

In this section, you’ll define two routes:

  • The route /crisis-center opens the crisis-center component.
  • The route /heroes-list opens the heroes-list component.

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

  • From your code editor, open the app.module.ts file.
  • Locate the @NgModule() section.
  • Replace the imports array in that section with the following.
imports: [
  BrowserModule,
  RouterModule.forRoot([
    {path: 'crisis-list', component: CrisisListComponent},
    {path: 'heroes-list', component: HeroesListComponent},
  ]),
],

This code adds the RouterModule to the imports array. Next, the code uses the forRoot() method of the RouterModule to define your two routes. This method takes an array of JavaScript objects, with each object defining the properties of a route. The forRoot() method ensures that your application only instantiates one RouterModule.

Update your component with router-outlet in Angular

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

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

  1. From your code editor, open the app.component.html file.
  2. Delete the following lines.
<app-crisis-list></app-crisis-list>
<app-heroes-list></app-heroes-list>

3. Add the router-outlet directive.

<router-outlet></router-outlet>

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

http://localhost:4200/crisis-list

Control navigation with UI elements in Angular

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

  1. Open the app.component.html file and add the following HTML below the title.
<nav>
  <a class="button" routerLink="/crisis-list">Crisis Center</a> |
  <a class="button" routerLink="/heroes-list">Heroes</a>
</nav>

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

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

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

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

Identify the active route in Angular for routing and navigation in angular

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

  1. From your code editor, open the app.component.html file.
  2. Update the anchor tags to include the routerLinkActive directive.
<nav>
  <a class="button" routerLink="/crisis-list" routerLinkActive="activebutton">Crisis Center</a> |
  <a class="button" routerLink="/heroes-list" routerLinkActive="activebutton">Heroes</a>
</nav>

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

Adding a redirect in Angular

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

  1. From your code editor, open the app.module.ts file.
  2. In the imports array, update the RouterModule section as follows.
imports: [
  BrowserModule,
  RouterModule.forRoot([
    {path: 'crisis-list', component: CrisisListComponent},
    {path: 'heroes-list', component: HeroesListComponent},
    {path: '', redirectTo: '/heroes-list', pathMatch: 'full'},
  ]),
],

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

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

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

Adding a 404 page in Angular

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

  1. From the terminal, create a new component, PageNotFound
ng generate component page-not-found

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

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

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

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

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

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

Now we can do routing and navigation in angular for our one page angular applications.

For more Angular Tutorials visit

If you like this, share this.

Follow us on FacebookTwitterTumblrLinkedIn, YouTube

YouTube Videos