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
- Query Params start after
?in URL - Multiple params are separated using
& - Use
ActivatedRouteto read query params queryParams.subscribe()is required to access values- Works with both links and buttons