ChatGPT解决这个技术问题 Extra ChatGPT

Angular 2 - Redirect to an external URL and open in a new tab

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 ?

If you can narrow it down to using Javascript, this should be a javascript question, not Angular2. Can you apply this solution stackoverflow.com/questions/19851782/… ?
@HarryNinh Angular 2 and 4 do not expose the window object inside a component (while you can get-away with using the window global, it's preferred to perform platform-specific tasks (like using the window object, which differs between browsers) using an Angular Service.

M
Martin Ocando
onNavigate(){
    window.open("https://www.google.com", "_blank");
}

Chrome is blocking popups when I use this method. Do you have any solution for that?
@sunnyiitkgp window.open() must be called within a callback which is triggered by a user action (example onclick).
@gokcand it is obvious, but it doesn't change the situation cause still is blocked as mentioned above.
Nothing beats good old vanilla javascript :)
S
SaoBiz

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');

I've been searching on and off for this for a week. In Angular 4 this works for me as a short term solution: , when it was treated as a route before. Thanks!
cant // suffice? eg: window.open(``//${this.urlToOpen}``, '_blank')
E
Ebrahiem Gamal

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');
}

d
dddenis

Another possible solution is:

const link = document.createElement('a');
link.target = '_blank';
link.href = 'https://www.google.es';
link.setAttribute('visibility', 'hidden');
link.click();

This method opens Link in new tab. " window.open(url, '_blank'); " open popup which is normally blocked by Chrome
M
Mile Mijatović

I want to share with you one more solution if you have absolute part in the URL

SharePoint solution with ${_spPageContextInfo.webAbsoluteUrl}

HTML:

<button (click)="onNavigate()">Google</button>

TypeScript:

onNavigate()
{
    let link = `${_spPageContextInfo.webAbsoluteUrl}/SiteAssets/Pages/help.aspx#/help`;
    window.open(link, "_blank");
}

and url will be opened in new tab.


I
Irrfan23

you can do like this in your typescript code

onNavigate(){
var location="https://google.com",
}

In your html code add an anchor tag and pass that variable(location)

<a href="{{location}}" target="_blank">Redirect Location</a>

Suppose you have url like this www.google.com without http and you are not getting redirected to the given url then add http:// to the location like this

var location = 'http://'+ www.google.com

U
Uğur Dinç

To solve this issue more globally, here is another way using a directive:

import { Directive, HostListener, ElementRef } from "@angular/core";

@Directive({
  selector: "[hrefExternalUrl]"
})
export class HrefExternalUrlDirective {
  constructor(elementRef: ElementRef) {}

  @HostListener("click", ["$event"])
  onClick(event: MouseEvent) {
    event.preventDefault();

    let url: string = (<any>event.currentTarget).getAttribute("href");

    if (url && url.indexOf("http") === -1) {
      url = `//${url}`;
    }

    window.open(url, "_blank");
  }
}

then it's as simple as using it like this:

<a [href]="url" hrefExternalUrl> Link </a>

and don't forget to declare the directive in your module.


p
prashanthglen
var url = "https://yourURL.com";
var win = window.open(url, '_blank');
    win.opener = null;
    win.focus();

This will resolve the issue, here you don't need to use DomSanitizer. Its work for me


L
Lijo

we can use target = blank to open in new tab

 <a href="https://www.google.co.in/" target="blank">click Here </a>

Well done! This is the simplest solution.