How to Open URL in New Tab using Angular ?
In this article, we will learn How to open a link in a new tab using Angular. A Link is a connection from one web page to another web page. Generally, the anchor tag can be used to open URLs in a new tab in an elementary and straightforward manner. However, the window.open() method can also be utilized to open a new browser window or a new tab depending on the browser setting and the parameter values.
Steps for Installing & Configuring the Angular Application
Step 1: Create an Angular application using the following command.
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname
Project Structure
It will look like the following:
Example 1: In this example, we will use a function window.open to open the link in a new tab.
HTML
<!-- app.component.html --> < h2 style = "color: green" >w3wiki</ h2 > < h2 >How to open a link in new tab using angular? </ h2 > < a (click)= "goToLink('https://www.w3wiki.net/Beginner-premier-league-gpl-2023/') " href = "" > Beginner Premier League </ a > |
Javascript
// app.component.ts import { Component } from '@angular/core' ; @Component({ selector: 'app-root' , templateUrl: "./app.component.html" , }) export class AppComponent { goToLink(url: string) { window.open(url, "_blank" ); } } |
Javascript
// app.module.ts import { NgModule } from '@angular/core' ; import { BrowserModule } from '@angular/platform-browser' ; import { HttpClientModule } from '@angular/common/http' ; import { FormsModule } from '@angular/forms' import { AppComponent } from './app.component' ; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, HttpClientModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
Output:
Example 2: In this example, we will be using target=”_blank”.
HTML
<!-- app.component.html --> < h2 style = "color: green" >w3wiki</ h2 > < h2 >How to open a link in new tab using angular? </ h2 > < a href = target = "_blank" > Beginner Premier League </ a > |
Javascript
// app.component.ts import { Component } from '@angular/core' ; @Component({ selector: 'app-root' , templateUrl: "./app.component.html" , }) export class AppComponent { } |
Javascript
// app.module.ts import { NgModule } from '@angular/core' ; import { BrowserModule } from '@angular/platform-browser' ; import { HttpClientModule } from '@angular/common/http' ; import { FormsModule } from '@angular/forms' import { AppComponent } from './app.component' ; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, HttpClientModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
Output