by Sai gowtham

Angular router query parameters (tutorial)

Home » angular » Angular router query parameters (tutorial)
Angular router query parameters (tutorial)

In this tutorial, we are going to learn about how to use query parameters in the angular router.

Query parameters

Query parameters are added to the end of URL with (?key=value) question mark followed by the key-value pairs by using that we can filter the data or we can use that data for other purposes.

Let’s see an example of how to use query parameters in routes.

    <a routerLink="/users" [queryParams]='{name:"sai"}'>User sai</a> </nav>

In the above code, we have added a new directive called queryParams to our users route.

queryParams : we need to pass our query parameters as an object to the queryParams directive.

Accessing query parameters data

To access the query parameters data inside UsersComponent we need to take the help of ActivatedRoute.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
  selector: 'app-userinfo',
  templateUrl: './userinfo.component.html',
  styleUrls: ['./userinfo.component.css']

export class UsersComponent implements OnInit {
  userName: string;  constructor(private route: ActivatedRoute) { }
  ngOnInit() {
     this.route.queryParams.subscribe(      (queryparams: Params) => {        this.userName =;      });  }

In the above code, we first imported ActivatedRoute service and Params type from the @angular/router package and we injected ActivatedRoute service to the component constructor so that we can use this service inside the component.

Inside ngOnInit method we are accessing the currently activated route queryParams data by subscribing it, and we are updating the userName property with currently loaded query params name. where name property is the same we added to the [queryParams]='{name:"sai"}' directive.