Need to open a link in a new tab within your Angular app? If so, then welcome to your own private little paradise.

I'll show you how to do it in this guide.

In fact, I'll show you a few ways to do it. Because I'm cool like that.

Let's get started.

The First Way

The first, and easiest way, is to just go with a straight HTML solution. It looks like this:

<a href="/dashboard" target="_blank">Click here</a>

The operative attribute there is target. Setting it to the value of "_blank" will open the link in a new tab. Assuming the user clicks on the anchor text of course.

Also note the href attribute. Its value is relative to the existing Angular application. 

For me, clicking that link opened this URL:

If you want to open an external link, you'll need to provide the full URL.

Also: if you're a fan of the routerLink directive, you could go this route (no pun intended):

<a [routerLink]="['/dashboard']" href="" target="_blank">Click here</a>

But I'd save that for when the target URL is derived from a variable.

The Second Way

It's possible that, for whatever reason, you're not able to do this within the template. You need to make it happen in component class code.

Good news: you can do it there, too.

First, put this in the template:

<a [routerLink]="" (click)="goToLink()">Click here</a>

That code follows the goToLink() method in the corresponding component class when the user clicks the link. I'll show you that code in a moment.

But you're probably wondering why the routerLink directive is there and why it points to an empty string.

It's a simple UI hack. Putting that directive there makes the text look clickable like any other anchor text. You can leave it out and the code will still work, but the text won't appear clickable even though it is.

Now, in the corresponding component class, look at this method:

  goToLink() {'/dashboard', '_blank');

That's using standard TypeScript. The open() method on the window object will point the browser to the given URL. 

But notice that the code is once again using '_blank'. That will force the new page to open in a separate tab just as it did before.

The Third Way

If you've got your hands on a Router service, you could go for something like this:

  goToLink() {
    const url = this.router.serializeUrl(
    );, '_blank');

That way you're letting the framework construct the URL string for you.

Wrapping It Up

There you have it. Three easy ways to open a page in a new tab within your Angular application.

Now feel free to take what you've learned here and start opening up a whole world of new possibilites. All in separate tabs.

Have fun!

Photo by Anete Lusina from Pexels