Angular 13 Send and Get Route Parameters Example

In this comprehensive angular routing parameter tutorial, you will learn how to pass the parameter in the route comfortably; equally important, get or access the parameter from the URL with the help of ActivatedRoute API.

The ActivatedRoute service allows access to data wherein a route is associated with a loaded component in an outlet.

Throughout this tutorial, you will find out how to send small chunks of data or information through URL or route from one component to another component.

We will create a simple angular blog application and create two components. Using these components, we will set a couple of routes; you will ascertain how to set route parameters in angular and pass parameters and access those params using the activated route’s snapshot param service.

Angular Passing and Getting Route Parameters Example

  • Create Angular App
  • Set Route Parameter with Slash in Angular
  • Check If Query Param Exists in Angular Route
  • Angular URL Parameter with Question Mark Example
  • Angular Route Parameter with Hash Separator Example

Create Angular App

Start the first step installing the new angular application ignore if app already installed:

ng new ng-demo

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, you have to manually disable the strict mode you can set “strict”: false, "noImplicitReturns": false and "strictTemplates": false inside the compilerOptions and angularCompilerOptions in tsconfig.json file.

Use command to generate new components:

ng generate component blog
ng generate component post-detail

Set Route Parameter with Slash in Angular

Setting parameters in the Route or URL is possible with slashes; you will see how to pass a parameter with slash separator inside the path property within the routes const:

http://www.positronx.io/post/5555/javascript

Here is the route structure in response to passing the parameters such as id and category in angular url:

Open the app-routing.module.ts file and update the below code:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { BlogComponent } from './blog/blog.component';
import { PostDetailComponent } from './post-detail/post-detail.component';

const routes: Routes = [
  {
      path: '',
      component: BlogComponent
  },
  {
    path: 'post/:postid/:category',
    component: PostDetailComponent
  }
 ];


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

export class AppRoutingModule { }

Access Route Parameter

Import ActivatedRoute from the ‘@angular/router’ module and inject it inside the constructor.

You will access the post id and category using the snapshot method and subscribe to paramMap.

Through this template you will learn how to get the parameter from the route.

Open and update below code in post-detail.component.ts file.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

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

export class PostDetailComponent implements OnInit {

  constructor(private actRoute: ActivatedRoute) { }

  ngOnInit(): void {
    let postid = this.actRoute.snapshot.params.postid;
    console.log(postid);

    let category = this.actRoute.snapshot.params.category;
    console.log(category);

    this.actRoute.paramMap.subscribe(res => {
      postid = res.get('postid');
      console.log(postid);
      
      category = res.get('category');
      console.log(category);
    });    
  }

}

Check If Query Param Exists in Angular Route

You can verify if the existing parameter for URL exists:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

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

export class PostDetailComponent implements OnInit {

  constructor(private actRoute: ActivatedRoute) { }

  ngOnInit(): void {
    let postid = this.actRoute.snapshot.params.postid;
    console.log(postid);

    if(postid === null){
      console.log('Post id param does not exist');  
    }

    let category = this.actRoute.snapshot.params.category;
    console.log(category);

    if(category === null){
      console.log('Post category param does not exist');  
    }       
  }

}

Angular URL Parameter with Question Mark Example

In the previous paradigm, we used a slash separator, but now you will see the usage of a question mark and ampersand in the angular route.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { BlogComponent } from './blog/blog.component';
import { PostDetailComponent } from './post-detail/post-detail.component';

const routes: Routes = [
  {
      path: '',
      component: BlogComponent
  },
  {
    path: 'post?postid=5555&category=javascript',
    component: PostDetailComponent
  }
];

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

export class AppRoutingModule { }

Here is the URL structure to display route with question mark and ampersand:

http://www.positronx.io/post?postid=5555&category=javascript
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

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

export class PostDetailComponent implements OnInit {

  constructor(private actRoute: ActivatedRoute) { }

  ngOnInit(): void {
    this.actRoute.queryParams.subscribe(params => {
      let postid = params['postid'];
      let category = params['category'];
      
      console.log(postid);
      console.log(category);
    });     
  }

}

Further, you will access the route params using the queryParams property of the activated route.

Angular Route Parameter with Hash Separator Example

Define the parameters in Angular Route using # Hash separator:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { BlogComponent } from './blog/blog.component';
import { PostDetailComponent } from './post-detail/post-detail.component';

const routes: Routes = [
  {
      path: '',
      component: BlogComponent
  },
  {
    path: 'post#postid=5555&category=javascript',
    component: PostDetailComponent
  }
];

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

export class AppRoutingModule { }

Generically, you might need the # Hash parameter in the route URL; here is the quick demo of angular hash parameter route example:

http://www.positronx.io/post#postid=5555&category=javascript

Next, you have to find out how to easily get the params property that we declared in the Hash fragment example

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

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

export class PostDetailComponent implements OnInit {

  constructor(private actRoute: ActivatedRoute) { }

  ngOnInit(): void {
    this.actRoute.fragment.subscribe((res: string) => {      
          const urlSearchParams = new URLSearchParams(res);
        
          const postid = urlSearchParams.get('postid')
          console.log(postid);
        
          const category = urlSearchParams.get('category')
          console.log(category);
      })
    }

}

Conclusion

We saw how to pass parameters and information to the Route. Over and above that, the Route parameters can be passed by using the routerLink parameters and the routerLink directive.

Moreover, we understood the nitty-gritty of ActivatedRoute Service for setting, passing, sharing param using the routes.