[英]How to open a link in new tab using angular?
我有一個需要在新選項卡中打開鏈接的 angular 5 組件,我嘗試了以下操作:
<a href="www.example.com" target="_blank">page link</a>
當我打開鏈接時,應用程序變慢並打開如下路線:
localhost:4200/www.example.com
我的問題是:以角度執行此操作的正確方法是什么?
使用window.open()
。 這很簡單!
在您的component.html
文件中-
<a (click)="goToLink("www.example.com")">page link</a>
在您的component.ts
文件中-
goToLink(url: string){
window.open(url, "_blank");
}
只需像這樣使用完整的 url 作為 href:
<a href="https://www.example.com/" target="_blank">page link</a>
<a [routerLink]="" (click)="openSite(SiteUrl)">{{SiteUrl}}</a>
並在您的 Component.ts 中
openSite(siteUrl) {
window.open("//" + siteUrl, '_blank');
}
我剛剛發現了一種使用路由器打開新選項卡的替代方法。
在你的模板上,
<a (click)="openNewTab()" >page link</a>
在你的 component.ts 上,你可以使用 serializeUrl 將路由轉換為字符串,它可以與window.open()
一起使用
openNewTab() {
const url = this.router.serializeUrl(
this.router.createUrlTree(['/example'])
);
window.open(url, '_blank');
}
只需將target="_blank"
到
<a mat-raised-button target="_blank" [routerLink]="['/find-post/post', post.postID]"
class="theme-btn bg-grey white-text mx-2 mb-2">
Open in New Window
</a>
在app-routing.modules.ts
文件中:
{
path: 'hero/:id', component: HeroComponent
}
在component.html
文件中:
target="_blank" [routerLink]="['/hero', '/sachin']"
某些瀏覽器可能會阻止window.open(url, "_blank");
創建的彈出窗口window.open(url, "_blank");
. 另一種方法是創建一個鏈接並單擊它。
...
constructor(@Inject(DOCUMENT) private document: Document) {}
...
openNewWindow(): void {
const link = this.document.createElement('a');
link.target = '_blank';
link.href = 'http://www.your-url.com';
link.click();
link.remove();
}
嘗試這個:
window.open(this.url+'/create-account')
無需使用'_blank'
。 window.open
默認在新選項卡中打開一個鏈接。
您可以嘗試綁定屬性 whit route
在你的 component.ts user:any = 'linkABC'
;
在你的 component.html <a target="_blank" href="yourtab/{{user}}">new tab </a>
你可以在你的代碼中添加 https,它對我有用
goToLink(url: string) {
window.open('https://' + url, "_blank");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.