How to Navigate to an External URL/Link in Angular?

In Angular, if we want to navigate to a link/URL on the same site where our Angular application is running, we use the navigate() method provided by the Angular Router.

For example:

// Navigates to internal links only 
this.router.navigate(['/all-blogs']);

But we can not use this method to redirect to external links.


Navigate to External Links using Window Object

To redirect a user to external links, you can use the window.open() method.

The window.open() method takes two parameters, first, the URL of the page where you want the user to redirect to and the second parameter specifies if you want the link to open in a new tab/window or in the same tab.

Let’s say we have a button in our template file. We want the user to navigate to google.com by clicking this button and also open this link in a new tab.

<h2>Click the button below to navigate to google.com</h2>
<button (click)="onBtnClick()">Visit Google</button>

Call the window.open() method on button click:

import { AfterViewInit, Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit{

  constructor() {}

  ngOnInit(): void {}

  onBtnClick(){
    
    // Open google.com in a new tab
    window.open('https://google.com', '_blank');

  }
  
}

Here is the output of the above code:

Navigate to an External URL/Link in Angular

If you want to open the external link in the same tab, you can pass ‘_self ‘ instead of ‘_blank’ as a second parameter to the window.open() method.

For example:

// Open google.com in the same tab
window.open('https://google.com', '_self');

That’s all for this article. Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts