我有一个Angular 5组件,需要在新标签页中打开链接,我尝试了以下方法:
<a href="www.example.com" target="_blank">page link</a>
当我打开链接时,应用程序变慢,并打开了如下路由:
localhost:4200/www.example.com
我的问题是: 在Angular中做这件事的正确方式是什么?
使用 window.open()
。这很简单!
在你的 component.html
文件中:
<a (click)="goToLink('www.example.com')">page link</a>
如果重定向不正确,您可能需要添加http
前缀:
<a (click)="goToLink('http://www.example.com')">page link</a>
component.ts
文件中:goToLink(url: string){
window.open(url, "_blank");
}
href=''
,这样它看起来仍然是可点击的。 - Leonardo Rick只需像这样将完整的 URL 用作 href:
<a href="https://www.example.com/" target="_blank">page link</a>
我刚刚发现了一种使用路由器在新标签页中打开的替代方法。
在您的模板中,
<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');
}
import { Router } from "@angular/router";
- undefined只需将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>
<a [routerLink]="" (click)="openSite(SiteUrl)">{{SiteUrl}}</a>
并且在你的Component.ts文件中
openSite(siteUrl) {
window.open("//" + siteUrl, '_blank');
}
downloadFile(){ const filePath = 'assets/files'; const fileName = '/myfile.xlsx'; const url =
${filePath}${fileName}; window.open(url, '_blank'); }
- C Alonso C Ortega一些浏览器可能会阻止通过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();
}
app-routing.modules.ts
文件中:{
path: 'hero/:id', component: HeroComponent
}
在 component.html
文件中:
target="_blank" [routerLink]="['/hero', '/sachin']"
试试这个:
window.open(this.url+'/create-account')
不需要使用'_blank'
。 window.open
默认在新选项卡中打开链接。
您可以在您的代码中添加 https,这对我有效。
goToLink(url: string) {
window.open('https://' + url, "_blank");
}
<a [routerLink]="" (click)="openSiteinNewTab()">click here to view</a>
export class AppComponent {
siteUrl = "stackoverflow.com";
openSiteinNewTab() {
window.open("//" + this.siteUrl, '_blank');
}
}
<a [href]="'www.example.com'" target="_blank">链接</a>
。 - Coach