Telerik blogs

Today we will look at how we can pass query parameters to the URL of our app using the routing module in Angular very easily.

Prerequisites

Developers of all levels, from beginners to experts can read this post—it does not matter if you are familiar with beginner concepts in Angular. Here are a few prerequisites you should have so you can 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
  • Version 12 of Angular

Other nice-to-haves include:

  • Working knowledge of the Angular framework at a beginner level

More Routing Concepts

So far we have looked at how to set up routing and other things like wildcard routes and even looked into the URL. Today we are looking at the URLs again and some things we are familiar with while browsing through web applications and mostly Google.com when querying for keywords. Does this look familiar?

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

See the query parameters from search and other queries too merged with the “&” character. Angular makes it easy for us to create these URLs that included the query parameters that suit our users’ navigation preferences.

What We Are Building

Today we are building a simple navbar component to show the query parameters in the URL when navigated to. Query parameters are used to pass optional params to the Angular route. Now let us get started with building it out.

Setting Up

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. Your folder should have an app component with two child components: about and contact. 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>

You can save your work and run the dev server to see that it all works well in the browser at localhost:4200.

ng serve

localhost:4200 adds a /about or /contact when we click on those names in the navigation, and a message shows ‘about works!’ or ‘contact works!’ respectively.

Adding Params

There are two ways to add params to your routes. The first way is inside the template, and the second way is programmatically in the component file. We are going to see these two approaches today.

Using the Template

We will modify the route and add some query params that talk about the part of the component and a search term too.

<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 }">About</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" [routerLink]="['/contact']">Contact</a>
  </li>
</ul>
<router-outlet></router-outlet>
</div>

You can see that we can use the query params options just like we can use the router link. If you use the template, the query params take an object where you can define the data you want to be displayed. For us, we display the part of the app, the search key and the current year.

Adding fragments to it is also pretty straightforward. Fragments are close to params but they are preceded by a hashtag in the URL while params are preceded by a question mark.

If you saved all the files and run the app on the dev server, you’ll see:

ng serve

Browser’s URL bar reads  ‘http://localhost:4200/about?part=navbar&search=about&year=2021#hello', and the page says  ‘about works!’

That is how to set up query params and fragments inside the desired template of your application.

Using the Component

You can also do this using TypeScript inside the component file. We will do the same exact setup except for the Contact page. First of all, we have to add the button and the onClick function to the About page. Paste in these lines below into the about HTML file:

<p>about works!</p>
<button (click)="movetoContact()">Go to Contact Page</button>

Now in the about component.ts file, paste this code block below:

import { Component, OnInit } from '@angular/core';
import {  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) { }
ngOnInit(): void {
  }
  movetoContact(){
    this.router.navigate(['/contact'],{queryParams: {part: 'navbar',search: 'contact', year: 2021 }})
  }
}

We brought in the router and then used the navigate function to achieve this.

We can also add fragments just like we did in the template file like this:

import { Component, OnInit } from '@angular/core';
import {  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) { }
ngOnInit(): void {
  }
  movetoContact(){
    this.router.navigate(['/contact'],{queryParams: {part: 'navbar',search: 'contact', year: 2021 },
  fragment: 'buttonClick'})
  }
}

Now if you save your files and go to the browser, it should look like this:

Browser’s URL bar reads  ‘http://localhost:4200/contact?part=navbar&search=contact&year=2021#buttonClick', and the page says  ‘about works!’

This is how to use query params and fragments to add parameters you can easily track in the URL of your application.

Wrapping Up

In today’s post we have looked into query params and fragments and how they can be used in handling some use cases in Angular. This post also sheds some light on how some of the links we see when navigating web apps were built and the features that Angular has provided to make them possible. 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.