typescript - Angular 2 - 重定向到外部 URL 並在新分頁中打開
我正在嘗試當用戶點擊連結時打開一個新頁面。我不能使用 Angular 2 路由,因為它沒有跳轉到外部 URL 的功能。
所以,我正在使用 window.location.href="...";
html 代碼:
<button (click)="onNavigate()">Google</tn-submenu-link>
TypeScript 程式碼:
onNavigate(){
//this.router.navigateByUrl("https://www.google.com");
window.location.href="https://www.google.com";
}
但是當使用 window.location.href 時,我該如何在新分頁中打開它?
答案#1
onNavigate(){
window.open("https://www.google.com", "_blank");
}
答案#2
使用 window.open() 的一個注意事項是,如果你傳給它的 URL 前面沒有 http:// 或 https://,Angular 會將其視為一個路由。
為了避免這個問題,檢查網址是否以 http:// 或 https:// 開頭,如果沒有,則加上它。
let url: string = '';
if (!/^http[s]?:\/\//.test(this.urlToOpen)) {
url += 'http://';
}
url += this.urlToOpen;
window.open(url, '_blank');
答案#3
在 HTML 中:
<a class="main-item" (click)="onNavigate()">Go to URL</a>
或
<button class="main-item" (click)="onNavigate()">Go to URL</button>
在 TS 檔案中:
onNavigate(){
// your logic here.... like set the url
const url = 'https://www.google.com';
window.open(url, '_blank');
}
答案#4
另一個可能的解決方案是:
const link = document.createElement('a');
link.target = '_blank';
link.href = 'https://www.google.es';
link.setAttribute('visibility', 'hidden');
link.click();
