October 15, 2024

Angular 10 – Routing

In this lesson we would cover Angular routing based on the following topics:

  1. What is Angular Routing
  2. Configuring Angular Routing
  3. Passing Information Across
  4. Setting up Redirects
  5. Handling Errors
  6. Child Routes

 

1. What is Angular Routing

Routing in Angular is the way pages web pages are served based on a given url. Since Angular focuses on SPA, the URLs are not served from the server and also don’t reload a page. The URLs are local in the browser and pages are served locally. Therefore, when a a URL is requested, the Angular router navigates to the new component. Then it renders it’s template and finally updates the history.

What is a Route?

A route in Angular is a pair of a url pattern and a component. Such that when a requested url matches the pattern, then a component is loaded.

 

2. Configuring Angular Routing

The file angular.routing.ts is responsible for routing in an Angular application. Follow the steps below to configure routing:

Step 1 – Import the AppRoutingModule into the AppModule. Also add it to the imports array. Normally this is done automatically by Angular CLI if routing is enabled for your application.

  imports: [
    BrowserModule,
    AppRoutingModule 
  ],

Step 2 – Import the RouterModel and Routes into app.routing.module.ts. Also done automatically.

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

 

Step 3 – Define the  routes in the Routes array.

The code below show route for three components

const routes: Routes = [
  { path: 'first-component', component: FirstComponent },
  { path: 'second-component', component: SecondComponent },
  { path: 'third-component', component: ThirdComponent },
];

Step 4 – Add the links to your template. This code below should be placed in the root component of the application (app.component.html).

<h1>Angular Routing Demo</h1>
<nav>
  <ul>
    <li><a routerLink="/first">1st Component</a></li>
    <li><a routerLink="/second">2nd Component</a></li>
    <li><a routerLink="/third">3rd Component</a></li>
  </ul>
</nav>
<!-- The routed views are rendered the <router-outlet>-->
<router-outlet></router-outlet>

 

3. Passing Information to Components

Sometimes, you may want to pass information from one component to another. For instance, in a shopping application that displays a list of products. When the user clicks on edit, the ProductEdit component is loaded. How do you pass data from the parent component to the ProductEdit component? The productId for example. You achieve this using the ActiveRoute interface. Here are the steps to follow:

Step 1: Import the ActiveRoute and ParamMap interfaces into your component. Like so

import { Router, ActivatedRoute, ParamMap } from '@angular/router';

 

Step 2: Inject an instance of the ActiveRoute. Just add an ActiveRoute field to your component constructor

constructor(
  private route: ActivatedRoute,
) {}

 

Step 3: In the ngOnInit() method, you can access the ActiveRoute and get the value of the productId variable. See below:

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

 

4. Handling Errors

When a user requests a path that does not exist, you should be able to handle this as well. You can achieve this by either using a Wildcard route and displaying a 404 page.

A wildcard routes represents a path using **. Then the component could be a custom component that displays a friendly error message.

  { path: '**', component: PageNotFoundComponent },  // Wildcard route

This route is selected if the requested url does not match any of the paths specified.

 

5. Redirects

You can also easily setup redirects in the same way. You simply specify the path you want to redirect from and the path you are redirecting to. See example below:

 { path: '/second', redirectTo: '/first', pathMatch: 'full' },

Here, when the user visits /second, he will be redirected to /first

 

6. Child Routes

For sizeable applications, you may want to create routes that are nested within other routes. For example a component may have several sub-components or child components and therefore you a child route would help.

A child or nested route is just like any other route and therefore has a path and a component. However, these routes are nested within other routes. An example is given below:

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

 

4.5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments