by Sai gowtham

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.

app.component.html
 <nav>
    <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.

users.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
@Component({
  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 = queryparams.name;      });  }
}

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.

queryparams.name where name property is the same we added to the [queryParams]='{name:"sai"}' directive.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course