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

前端 未结 9 688
离开以前
离开以前 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');
    

提交回复
热议问题