Telerik blogs
AngularT2_Light_1200x303

In this post, we are going to look into how you can retrieve data from URL query parameters in Angular inside the component using the Router module.

Before We Start

This post is suited for all levels of frontend developers who use Angular, so being conversant with beginner concepts and installation processes is not assumed. Here are a few prerequisites you should have to follow along through this article’s demonstration:

  • An integrated development environment like VS Code
  • Node version 11.0 installed on your machine
  • Node Package Manager version 6.7 (it usually ships with Node installation)
  • Angular CLI version 8.0 or above
  • A recent version of Angular (this post uses Angular 12)

Other nice-to-haves include:

  • Working knowledge of the Angular framework at a beginner level

More Routing Concepts

In the last post, we looked at query params and understood how URLs like the one below are made using the Angular Router.

https://www.google.com/search?q=query+params+angular&oq=query+params+angular

What We Are Building

Today, we are going to work on a Navbar component with the about and contact components and use the query params and then retrieve the details inside one of the components. We are going to continue from the last post, so download the source file from here into your machine.

Open the new file in VS Code and inside the terminal run the command below:

npm install

This ensures all the Node modules and dependencies needed for the project are properly installed. The app component.html file should look like this:

<div class="container">
<ul class="nav justify-content-center">
  <li class="nav-item">
    <a class="nav-link active" aria-current="page" href="/">Home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" [routerLink]="['/about']">About</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" [routerLink]="['/contact']">Contact</a>
  </li>
</ul>
<router-outlet></router-outlet>
</div>

Defining Parameters

Now to add params, which we will retrieve in our component later in the post. Navigate to the app component.html page and paste the code block below inside:

<div class="container">
<ul class="nav justify-content-center">
  <li class="nav-item">
    <a class="nav-link active" aria-current="page" href="/">Home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" 
    [routerLink]="['/about']"
    [queryParams]="{part: 'navbar',search: 'about', year: 2021 }"   [fragment]='"hello"'>About</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" [routerLink]="['/contact']">Contact</a>
  </li>
</ul>
<router-outlet></router-outlet>
</div>

Now if you save all the files in the project and run the app on your dev server, it should look like this:

Clicking on the About and Contact pages will update the URL to show ? and # for params and fragments as demonstrated in the previous article

You can see the query params and the fragment showing in the URL as we want it to.

Getting the Data

Now that we have sent the parameters and the fragment and confirmed it shows up in the URL, let’s try getting the data and even displaying it in the template. Your about component file should look like this:

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-about',
  templateUrl: './about.component.html',
  styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {
constructor() { }
ngOnInit(): void {
  }
}

Now let us bring in the activated route as we are trying to take a snapshot of what the query parameters look like and also what the fragment in the URL looks like. Query params return an object, while fragments return a string.

We can test it by just logging the values:

console.log(this.route.snapshot.queryParams);
console.log(this.route.snapshot.fragment);

Remember you have to bring in the activated route to use the snapshot option:

import { Component, OnInit } from '@angular/core';
import {  ActivatedRoute, Router } from '@angular/router';
@Component({
  selector: 'app-about',
  templateUrl: './about.component.html',
  styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {
constructor(private router: Router, private route: ActivatedRoute) { }
ngOnInit(): void {
    console.log(this.route.snapshot.queryParams);
    console.log(this.route.snapshot.fragment);
  }
}

Your about component should have a return like this in the browser console:

navbar-results part: navbar, search: about, year: 2021

Displaying the Data

We have gotten the data from the URL—now is there a way we can display it in our template instead of in the browser console? Copy the code block below inside the about component.ts file:

import { Component, OnInit } from '@angular/core';
import {  ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-about',
  templateUrl: './about.component.html',
  styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {
  details: { year:number; part: string; greeting:string}
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
    console.log(this.route.snapshot.queryParams);
    console.log(this.route.snapshot.fragment);
this.details = {
      part: this.route.snapshot.queryParams['part'],
      year: this.route.snapshot.queryParams['year'],
      greeting: this.route.snapshot.fragment
    }
  }
}

Now we created a details object and have variables for parts of the query params and the fragment, and we tied the variables to the snapshots of the data we already got.

The next thing to do is to display the data in the template, so let us change the code block in the presentation.

Navigate to the about component’s HTML file and replace the content with the code block below:

<div>
    <p>This is the about Page</p>
    <p>{{details.greeting}}, you are currently inside the {{details.part}} for the app and this was built in {{details.year}}</p>
</div>

We have now used data binding to bind the data we have to the template and embedded it into a paragraph.

Now if you save all the files and check your browser at localhost:4200, you should see it show up like this:

The About page now says,  ‘This is the about page. hello, you are currently inside the navbar for the app and this was built in 2021’

That is how to get data from the query params and fragments in any Angular URL, customize and display the content inside the template.

Conclusion

In today’s post, we have seen how query params and fragments inside the URL can be retrieved and even displayed in our application easily using the Angular Router. There are a lot of ways and use cases where you can apply this in your applications. Happy hacking!


5E9A474B-EBDB-439E-8A4A-3B041B0BEDA6
About the Author

Nwose Lotanna Victor

Nwose Lotanna Victor is a web technology enthusiast who documents his learning process with technical articles and tutorials. He is a freelance frontend web developer based in Lagos, Nigeria. Passionate about inclusion, community-building and movies in Africa, he enjoys learning new things and traveling.

Related Posts

Comments

Comments are disabled in preview mode.