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

前端 未结 9 546
离开以前
离开以前 2020-12-03 00:36

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.

<
相关标签:
9条回答
  • 2020-12-03 00:48

    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');
    
    0 讨论(0)
  • 2020-12-03 00:51
    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

    0 讨论(0)
  • 2020-12-03 00:52
    onNavigate(){
        window.open("https://www.google.com", "_blank");
    }
    
    0 讨论(0)
  • 2020-12-03 00:54

    we can use target = blank to open in new tab

     <a href="https://www.google.co.in/" target="blank">click Here </a>
    
    0 讨论(0)
  • 2020-12-03 00:57

    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.

    0 讨论(0)
  • 2020-12-03 01:00

    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.

    0 讨论(0)
提交回复
热议问题