Angular Routing: How to Navigate With Code
Angular Routing Navigation Components Parameters Protect Routes Angular Router Code Tutorial Guide

José Matos

25 Mar 2023

Angular Routing: How to Navigate With Code

    Angular Routing: How to Navigate With Code

    As an Angular developer, understanding how to navigate between pages within an application is crucial. In Angular, this is accomplished through routing. The Angular Router is a powerful mechanism that enables you to navigate between components, pass parameters between them, and even protect routes from unauthorized access. In this article, we will discuss how to navigate between components in an Angular application using code.

    What is Routing?

    Routing is the navigation mechanism within Angular applications. It is responsible for deciding which component to display based on the current URL. Angular apps are made up of components and components are organized into a hierarchy. Routing defines the hierarchy and maps URLs to different components. In Angular routing, components are the building blocks or “pages” of the application.

    Creating a Routing Module

    To use the routing functionality, you must create a routing module. A routing module is a module that declares the routes used in your application. To create a routing module in your Angular application, execute the following command:

    ng generate module app-routing --flat --module=app

    The command will create a new file named ‘app-routing.module.ts’ in the ‘src/app’ directory. By convention, this file is the routing module of your application.

    Defining the Routes

    To define routes for your application, you need to import the ‘Routes’ interface from Angular Router module and define an array of ‘Route’ objects. Each route object defines a path & a component to display when the path is matched. Here’s an example:

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { HomeComponent } from './home/home.component';
    import { AboutComponent } from './about/about.component';
    
    const routes: Routes = [
      { path: '', component: HomeComponent },
      { path: 'about', component: AboutComponent },
      { path: '**', component: HomeComponent }
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }

    In the code above, we import the ‘Routes’ interface, ‘RouterModule’, and the components that we will use in our routes. The ‘routes’ array defines two routes: one for the home component and the other for the about component. We have also defined a wildcard route ‘**’ that will redirect to the home component if the requested URL is not found. Finally, we create a new module and import the ‘RouterModule’, which provides the routing module that we need to use for our application.

    Navigating to a Component using Code

    Now, let’s see how to navigate to the about component using code. To navigate to a component, we need to inject the ‘Router’ service into our component and call the ’navigate()’ method on it. Here’s an example:

    import { Component } from '@angular/core';
    import { Router } from '@angular/router';
    
    @Component({
      selector: 'app-home',
      template: `
        <h1>Home Component</h1>
        <button (click)="goToAbout()">Go to About</button>
      `
    })
    export class HomeComponent {
      constructor(private router: Router) { }
    
      goToAbout() {
        this.router.navigate(['/about']);
      }
    }

    In this example, we import the ‘Router’ service and inject it into our component using dependency injection. Then, we create a method ‘goToAbout()’ which calls the ’navigate()’ method of the ‘Router’ service and navigates to the ‘/about’ path.

    The navigate() Method

    The ’navigate()’ method takes an array of URL segments that make up the path to the component. In our example, we pass the ‘/about’ path to the ’navigate()’ method. Alternatively, you can pass the same path as a string. Here’s an example:

    this.router.navigate('/about');

    Passing Parameters to a Component

    You may need to pass parameters to a component while navigating. To pass parameters, you can add an array of key-value pairs as a second argument to the ’navigate()’ method. Here’s a simple example:

    this.router.navigate(['/user', userId]);

    In the code above, we pass a URL segment ‘/user’ and the ‘userId’ parameter to the ’navigate()’ method. The URL will look like ‘/user/123’, where 123 is the value of the ‘userId’ variable.

    Retrieving Parameters in a Component

    To retrieve the parameter in a component, import the ‘ActivatedRoute’ service and subscribe to the ‘params’ observable to access the parameter value. Here’s an example:

    import { Component, OnInit } from '@angular/core';
    import { ActivatedRoute } from '@angular/router';
    
    @Component({
      selector: 'app-user',
      template: `
        <h1>User Component</h1>
        <p>User ID: {{ userId }}</p>
      `
    })
    export class UserComponent implements OnInit {
      userId: number;
    
      constructor(private route: ActivatedRoute) { }
    
      ngOnInit() {
        this.route.params.subscribe(params => this.userId = params['id']);
      }
    }

    In this example, we import the ‘ActivatedRoute’ service and inject it into our component using dependency injection. Then, we subscribe to the ‘params’ observable to retrieve the value of the ‘id’ parameter.

    Conclusion

    In this article, we have discussed how to navigate between components in an Angular application using code. We have learned how to create a routing module, define routes, and navigate to a component using code. We have also seen how to pass parameters to a component and retrieve them. Angular routing is a powerful mechanism that enables you to navigate between components, pass parameters between them, and even protect routes from unauthorized access. With this knowledge, you can create complex Angular applications with ease.

    © 2023 Designed & Developed by José Matos.