Open In App

How to pass query parameters with a routerLink ?

The task is to pass query parameters with a routerLink, for that we can use the property binding concept to reach the goal. Using property binding, we can bind queryParams property and can provide the required details in the object.

What is Property Binding?



It is a concept where we use square bracket notation to bind data to Document Object Model(DOM) properties of Hypertext markup language(HTML) elements.

Syntax:



<a [routerLink]="[/path]" [queryParams]="{property:value}">
   State Details 
</a>
 

An Example of property binding:




import { Component, OnInit } from '@angular/core'
  
@Component({
  
    selector: 'app-property',
    template:
        // Property Binding 
        `<p [textContent]="title"></p>`
})
  
export class AppComponent implements OnInit {
  
    constructor() { }
    ngOnInit() { }
  
    title = 'Property Binding example in GeeksforGeeks';
  
}

Output:

Illustration of above code

Approach:

Below is the implementation of the above steps:

app.module.ts:




import { NgModule } from '@angular/core';
import { BrowserModule } from 
            '@angular/platform-browser';
  
// Importing Routes
import { RouterModule, Routes } 
        from '@angular/router';
  
import { AppComponent } from 
            './app.component';
  
import { StateComponent } from 
        './state/state.component';
  
// Configuring Routes
const routes: Routes = [{ 
    path: 'punjab'
    component: StateComponent 
},];
  
@NgModule({
    imports: [BrowserModule, R
        outerModule.forRoot(routes)],
          
    declarations: [AppComponent, 
        StateComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html:




<a [routerLink]="['/punjab']" [queryParams]=
    "{capital:'mohali',language:'punjabi'}">
    State Details
</a>
<router-outlet></router-outlet>

After clicking on the anchor tag the URL will be displayed in the following way:

We can also access the query parameters using the activated route.

In this way, we can pass query parameters via routerLink.

Fetching of query parameters:

state.component.ts :




import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
  
@Component({
  selector: 'app-state',
  templateUrl: './state.component.html',
  styleUrls: ['./state.component.css']
})
export class StateComponent implements OnInit {
  
  capital: string;
  language:string;
  
  constructor(private route: ActivatedRoute) { }
  
  ngOnInit() {
    this.route.queryParams.subscribe(
      params => {
        this.capital =  params['capital'];
        this.language=params['language'];
      }
    )
  }
  
}

state.component.html:




State Details are : 
  
<p>Capital  : {{capital}} </p>
  
<p>Language : {{language}} </p>

Output:


Article Tags :