Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Angular read query string parameters

Suggested Videos
Part 49 - Angular impure pipe | Text | Slides
Part 50 - Data filter in angular component | Text | Slides
Part 51 - Angular query params | Text | Slides

In this video we will discuss, how to read query string parameters in Angular

To read query parameters we use ActivatedRoute service. We use this same service to read required and optional route parameters.


Inject the ActivatedRoute service using the component class constructor
constructor(private _route: ActivatedRoute) { }


Depending on your project requirements, you can then use either the snapshot approach or the observable approach. We discussed the difference between these 2 approaches and when to use one over the other in Part 42 of this Angular CRUD tutorial.

In Angular there are 3 types of parameters.
  • Required parameters
  • Optional parameters
  • Query parameters
When working with any of these parameters, the following properties and methods are very useful.
Member Description
has(name) Returns true if the parameter is present and false if not. Very useful to check for the existence of optional route and query parameters
get(name) Returns the parameter value as a string if present, or null if not present in the map. Returns the first element if the parameter value is an array of values
getAll(name) Returns a string array of the parameter value if found, or an empty array if the parameter is not present in the map. Use getAll when a single parameter could have multiple values
keys Returns a string array of all the parameters in the map

Please note : For required and optional route parameters, we use the paramMap property of the ActivatedRoute object and for Query Parameters, we use queryParamMap property.

Use the snapshot approach if the query params does not change during the lifetime of this component.

if (this._route.snapshot.queryParamMap.has('searchTerm')) {
  this.searchTerm = this._route.snapshot.queryParamMap.get('searchTerm');
} else {
  this.filteredEmployees = this.employees;
}

On the other hand, if you expect the query parameter value to change during the life time of this component, and if you want to react and execute some code in response to that change, then use the Observable approach.

this._route.queryParamMap.subscribe((queryParams) => {
  if (queryParams.has('searchTerm')) {
    this.searchTerm = queryParams.get('searchTerm');
  } else {
    this.filteredEmployees = this.employees;
  }
});

angular crud tutorial

No comments:

Post a Comment

It would be great if you can help share these free resources