It's more difficult than it should be. But not that difficult.

In this guide, I'll show you how to include an anchor tag (<a>) in your HTML template that links to a route with a request parameter.

So you can send the user to a URL that looks like this:


See that id request parameter at the end? That's probably what brought you here.

Once you're done reading this guide, you'll not only know how to do something that simple, but also understand the pattern so you can stick the landing every time.

Let's get started.

The Problem

You might think it's easy to add an anchor tag with a request parameter in the URL.

Of course, if you did think that, you probably wouldn't be reading this (welcome to this site from whichever search engine brought you here).

Anyhoo, if a search engine didn't bring you here, you might think that you could just do this in your HTML:

<a href="/contacts/view-contact?id=6014199147692f2a4194ff95">Lucy Cheng</a>

That seems like it would work, right?

Nope. The problem is that Angular will encode that URL. So it ends up looking like this: 


The question mark gets replaced with %3F. That ain't gonna work.

So you need to do things the Angular way. Like I said above, it's harder than it should be but not that hard.

The Angular Way

TL;DR just do it like this:

<a [routerLink]="['/contacts/view-contact']" [queryParams]="{id:}">{{}} {{}}</a>

Now let me explain what's going on there.

First of all, note the use of brackets. That's for binding to properties defined in the related component class.

However, for [routerLink], the value is simply hardcoded to the base URL because there's no need to define that in the component. 

Just make a note of the syntax. It's an array of a single string. 

But that's just the base URL. You still need the request parameter.

That's why [queryyParams] exists.

However, that one's not a simple string. It's a JSON object.

Each property in the JSON object is a request parameter. Each value in the JSON object is the value of the associated request parameter.

So if in the component class equals '6014199147692f2a4194ff95' then {id:} becomes id=6014199147692f2a4194ff95 as a request parameter.

And the whole URL looks like this:


Which is exactly what you want. No more encoding.

Now, when users click on that link, they'll go to the correct route with the associated request parameter.

And yes, you can specify multiple request parameters with standard JSON encoding, like this:

<a [routerLink]="['/contacts/view-contact']" [queryParams]="{id:, userId:}">{{}} {{}}</a>

If is 37 in the component class, then that link will look like this:


Wrapping It Up

Now that you've got the pattern down, you can add links to your heart's content 

If you want to see the Angular docs on the subject, click here.

But whatever you do, just make sure you have fun!

Photo by Andrea Piacquadio from Pexels