首页 文章

Angular 2 - 重定向到外部URL并在新选项卡中打开

提问于
浏览
36

我正在尝试在用户点击链接时打开新页面 . 我不能使用Angular 2路由器,因为它没有任何功能可以重定向到外部URL .

所以,我正在使用window.location.href =“...”;

HTML代码:

<button (click)="onNavigate()">Google</tn-submenu-link>

打字稿代码:

onNavigate(){
        //this.router.navigateByUrl("https://www.google.com");
        window.location.href="https://www.google.com";
    }

但是如何在新标签中打开它?什么时候使用window.location.href?

6 回答

  • 64

    我们可以使用target = blank在新标签中打开

    <a href="https://www.google.co.in/" target="blank">click Here </a>
    
  • 0
    onNavigate(){
        window.open("https://www.google.com", "_blank");
    }
    
  • 13

    另一种可能的解决方案

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

    你可以在打字稿代码中这样做

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

    在你的html代码中添加一个锚标记并传递该变量(位置)

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

    关于使用 window.open() 的一个警告是,如果传递给它的url在它前面没有 http://https:// ,则angular会将其视为路径 .

    要解决这个问题,请测试url是以 http:// 还是 https:// 开头,如果不是则附加它 .

    let url: string = '';
    if (!/^http[s]?:\/\//.test(this.urlToOpen)) {
        url += 'http://';
    }
    
    url += this.urlToOpen;
    window.open(url, '_blank');
    
  • 5

    如果您对URL有绝对的参与,我想再与您分享一个解决方案

    使用 ${_spPageContextInfo.webAbsoluteUrl} 的SharePoint解决方案

    HTML:

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

    打字稿:

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

    和url将在新标签页中打开 .

相关问题