Angular 13 | How to Get Query Param in URL

In this tutorial, you will learn how to quickly get query params from application URL separated by? (question mark) and & (ampersand) characters.

We usually pass URL params in the Angular application, but for some use-cases, we also append query params in the application URL for example:

example.com/buy/classicway/indoor?style=classic&type=modular

In the above URL style and type are the appended query params.

How to get query params in the Angular application?

You can subscribe to the queryParams observable provided by ActivatedRoute as shown below:

Step 1) Import RouterModule

Step 2) Import ActivatedRoute Class

Step 3) Subscribe to queryParams Observable

 

Step 1) Import RouterModule

Before using router classes, you need to import the RouterModule inside your AppModule. open the app.module.ts file and import the RouterModule.forRoot([]) inside the imports array as shown below:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule, 
    RouterModule.forRoot([]) //<---Added here
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

 

Step 1) Import ActivatedRoute Class

Inside the component class, import the ActivatedRoute class available in @angular/router component

import { ActivatedRoute } from '@angular/router';

 

Now define inside the class constructor

constructor(
    private activatedRoute: ActivatedRoute
    ) {}

 

Step 2) Subscribe to queryParams Observable

Next, we deen to add the subscription inside the ngOnInit()

ngOnInit() {
    this.activatedRoute.queryParams.subscribe((params) => {
      let style = params['style'];
      let type = params['type'];

      console.log(style); // OUTPUT 123
      console.log(type); // OUTPUT modular
    });
  }

Complete HTML Template

<H1>

    You are at <span style="color:red;">{{style}}</span> style with <span style="color:blue;">{{type}}</span> type

</H1>

The final component class at app.component.ts file will look like this:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  style!: string;
  type!: string;

  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.activatedRoute.queryParams.subscribe((params) => {
      this.style = params['style'];
      this.type = params['type'];
    });
  }
}

 

Leave a Comment

Your email address will not be published. Required fields are marked *