Angular 16 ActivatedRoute Route Tutorial with Example

Last Updated on by in Angular
In this tutorial you will learn about Angular ActivatedRoute interface class with example, Angular offers ActivatedRoute interface class.It carries the information about a route linked to a component loaded into the Angular app template.

An ActivatedRoute contains the router state tree within the angular app’s memory.

Set up Angular Project

Install the Angular CLI with below command.

npm install @angular/cli -g

Now, you have to install the brand new Angular project using below command.

ng new angular-demo

Angular CLI asks for your choices while setting up the project…

Would you like to add Angular routing?
Select y and Hit Enter.

Which stylesheet format would you like to use? (Use arrow keys)
Choose SCSS and hit Enter

Use command to navigate into the project directory:

cd angular-demo

Remove Angular TypeScript Errors

Make sure to remove strict type warnings or error make sure to set following properties to false in tsconfig.json file:

"compilerOptions": {
 ...
 ...
   "strict": false,
   "noPropertyAccessFromIndexSignature": false,
 ...
 ...
},
  "angularCompilerOptions": {
    "strictTemplates": false
  }

Understand ActivatedRoute Interface Class Properties

  • Snapshot – This is the current snapshot of this route.
  • URL – It is an observable of the URL segments and it matched by this route
  • Params – Observable of the matrix parameters scoped to this route
  • QueryParams – Observable of the query parameters shared by all the routes
  • Fragment – Observable of the URL fragment shared by all the routes
  • Data – Observable of the static and resolved data of this route.
  • Root – This is the root of the router state
  • Parent – This property is the parent of this route in the router state tree
  • FirstChild – First child of this route in the router state tree
  • Children – Children of this route in the router state tree
  • pathFromRoot – Path from the root of the router state tree to this route
  • paramMap – It is read-only
  • queryParamMap – It is read-only
  • Outlet – It’s a constant and outlet name of the route
  • Component – It’s a constant and a component of the route
  • RouteConfig – This configuration used to match this route
Run the following command to generate student interface class for setting up data types.

ng g i student

Afterwards, go to student.ts file and add the following code into it.

export interface Student {
   $key: string;
   firstName: string;
   lastName: string;
   email: string
   mobileNumber: Number;
}

Generate crud.service.ts

This file hold the GetStudent() method which will get student from database.

import { Injectable } from '@angular/core';
import { Student } from './student'; // Student data type interface class
import {
  AngularFireDatabase,
  AngularFireObject,
} from '@angular/fire/compat/database'; // Firebase modules for Database, Data list and Single object

@Injectable({
  providedIn: 'root',
})

export class CrudService {
  studentRef: AngularFireObject<Student>; // Reference to Student object, its an Observable too

  // Inject AngularFireDatabase Dependency in Constructor
  constructor(private db: AngularFireDatabase) {}

  // Fetch Single Student Object
  GetStudent(id: string) {
    this.studentRef = this.db.object('students-list/' + id);
    return this.studentRef;
  }
}

Use ActivatedRoute Service to Get Current Id

Import ActivatedRoute from “@angular/router”, ActivatedRoue is used to get the current associated component’s information.

import { Component } from '@angular/core';
import { CrudService } from './crud.service';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})

export class AppComponent {
  constructor(
    private crudApi: CrudService, // Inject CRUD API in constructor
    private actRoute: ActivatedRoute // Activated route to get the current component's information
  ) {}

  ngOnInit() {
    const id = this.actRoute.snapshot.paramMap.get('id'); // Getting current component's id or information using ActivatedRoute service
    this.crudApi
      .GetStudent(id)
      .valueChanges()
      .subscribe((data) => {
        console.log(data) // Using SetValue() method, It's a ReactiveForm's API to store initial value of reactive form
      });
  }
}

The following command will start a development server, compile and run your app.

ng serve --open