Hello, and welcome to another exciting lesson on Angular! Today, we're going to explore Query Parameters. Query parameters are a key part of URLs, and they allow us to pass data from one component to another. They are particularly useful when navigating between components in Angular.
In simple terms, query parameters are additional information that is appended to the URL after a ? symbol. This extra data helps us customize the content displayed by a web application based on the user's preferences or requirements.
A typical URL structure with query parameters might look like this:
http://example.com/components/user-profile?name=JohnDoe&age=30
In this example, name=JohnDoe and age=30 are query parameters.
To access query parameters in Angular, we can use the ActivatedRoute service provided by Angular's Router Module.
Here's a step-by-step guide on how to access query parameters:
ActivatedRoute service in your component's constructor.import { ActivatedRoute } from '@angular/router';
constructor(private activatedRoute: ActivatedRoute) { }queryParams and queryParamsMap methods.ngOnInit() {
this.activatedRoute.queryParams.subscribe(params => {
console.log(params);
});
this.activatedRoute.queryParamsMap.subscribe(params => {
console.log(params);
});
}In the example above, params will contain the query parameters as an object.
Let's create a simple example where we pass a query parameter to display a specific user's details.
user-details:ng generate component user-detailsuser-details.component.ts file, inject the ActivatedRoute service and access the query parameters.import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-user-details',
templateUrl: './user-details.component.html',
styleUrls: ['./user-details.component.css']
})
export class UserDetailsComponent implements OnInit {
userName: string;
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit() {
this.activatedRoute.queryParams.subscribe(params => {
this.userName = params['name'];
});
}
}user-details.component.html, display the user's name using the userName property.<h1>User Details for: {{ userName }}</h1>user-details component with a query parameter in the main app component's ngOnInit method:import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.navigate(['/user-details'], { queryParams: { name: 'JohnDoe' } });
}
}Which service do we use to access query parameters in Angular?
With this lesson, you now understand what query parameters are and how to access them in Angular. Happy coding! 🎉