Query Parameters Explained | Pass & Read Data Using URL

What are Query Params?

Query Params are used to send data from one page to another through the URL.


Example URL:

/profile?id=1&name=Anil&age=29


Send Query Params using RouterLink (Home Page)

home.ts

import { Component, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterLink } from '@angular/router';

@Component({
selector: 'app-home',
standalone: true,
imports: [CommonModule, RouterLink],
templateUrl: './home.html'
})
export class Home {
userData = signal({
id: 1,
name: 'Anil',
age: 29
});
}


home.html

<a
routerLink="/profile"
[queryParams]="{
id: userData().id,
name: userData().name,
age: userData().age
}"
>
Go to Anil Profile
</a>


Read Query Params (Profile Page)

profile.ts

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

@Component({
selector: 'app-profile',
standalone: true,
imports: [CommonModule],
templateUrl: './profile.html'
})
export class Profile implements OnInit {
name = signal('');
age = signal(0);
id = signal(0);

constructor(public route: ActivatedRoute) {}

ngOnInit() {
this.route.queryParams.subscribe(params => {
this.name.set(params['name']);
this.age.set(params['age']);
this.id.set(params['id']);
});
}
}

profile.html

<ul>
<li>Name: {{ name() }}</li>
<li>Age: {{ age() }}</li>
<li>ID: {{ id() }}</li>
</ul>


Send Query Params on Button Click

home.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router';

@Component({
selector: 'app-home',
standalone: true,
imports: [CommonModule],
templateUrl: './home.html'
})
export class Home {
constructor(public router: Router) {}

goToProfile() {
this.router.navigate(['profile'], {
queryParams: {
id: 10,
name: 'Peter',
age: 40
}
});
}
}


home.html

<button (click)="goToProfile()">Go to Profile</button>


Important Points

  1. Query Params start after ? in URL
  2. Multiple params are separated using &
  3. Use ActivatedRoute to read query params
  4. queryParams.subscribe() is required to access values
  5. Works with both links and buttons