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.
<!-- app.component.html --> < h2 style = "color: green" >GeeksforGeeks</ h2 >
< h2 >How to open a link in new tab using angular? </ h2 >
< a (click)=
href = "" >
Geeks Premier League
</ a >
|
// 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" );
}
} |
// 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”.
<!-- app.component.html --> < h2 style = "color: green" >GeeksforGeeks</ h2 >
< h2 >How to open a link in new tab using angular? </ h2 >
< a href =
target = "_blank" >
Geeks Premier League
</ a >
|
// app.component.ts import { Component } from '@angular/core' ;
@Component({ selector: 'app-root' ,
templateUrl: "./app.component.html" ,
}) export class AppComponent { } |
// 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