I'm trying to Open a new page when user clicks on a link. I can't use Angular 2 Router, because it doesn't have any functionalities to redirect to an external URL.
so, i'm using window.location.href="...";
html code:
<button (click)="onNavigate()">Google</tn-submenu-link>
typescript code:
onNavigate(){
//this.router.navigateByUrl("https://www.google.com");
window.location.href="https://www.google.com";
}
But how can I open it in a new tab? when using window.location.href ?
onNavigate(){
window.open("https://www.google.com", "_blank");
}
One caveat on using window.open() is that if the url that you pass to it doesn't have http:// or https:// in front of it, angular treats it as a route.
To get around this, test if the url starts with http:// or https:// and append it if it doesn't.
let url: string = '';
if (!/^http[s]?:\/\//.test(this.urlToOpen)) {
url += 'http://';
}
url += this.urlToOpen;
window.open(url, '_blank');
in HTML:
<a class="main-item" (click)="onNavigate()">Go to URL</a>
OR
<button class="main-item" (click)="onNavigate()">Go to URL</button>
in TS file:
onNavigate(){
// your logic here.... like set the url
const url = 'https://www.google.com';
window.open(url, '_blank');
}