如何在TypeScript中使用router.navigate打开新选项卡

Dan*_*lle 5 knockout.js single-page-application typescript durandal

以下打字稿代码将始终在当前浏览器选项卡中打开

navigate($data: menuItem, $event: JQueryEventObject) {
       //...
       let a = $event.currentTarget as HTMLAnchorElement;
       router.navigate(a.href);    
    }
Run Code Online (Sandbox Code Playgroud)

如何在标签页中打开router.navigate ?(即$ event.ctrlKey为true时)

har*_*key 29

这是我的解决方案

const url = this.router.serializeUrl(this.router.createUrlTree(['/my/url/route'], { queryParams: { ...anyQueryParamsYouWantOrOmitThis } }));
window.open(url, '_blank');
Run Code Online (Sandbox Code Playgroud)


Tha*_*ran 9

是的,正如您@Daneille 评论的那样,您必须以自己的方式处理,因为 durandal 的路由器插件(导航功能)不提供打开新标签的方法。

所以最好按照你的评论处理一些事情。

if ($event.ctrlKey) { 
    window.open(url); 
}
Run Code Online (Sandbox Code Playgroud)


Kam*_*ski 9

这个适用于 # 哈希(如https://example.com/#/users)和非哈希网址

openInNewTab(router: Router, namedRoute) {
    let newRelativeUrl = router.createUrlTree([namedRoute]);
    let baseUrl = window.location.href.replace(router.url, '');

    window.open(baseUrl + newRelativeUrl, '_blank');
}
Run Code Online (Sandbox Code Playgroud)


MNF*_*MNF 5

我认为最好在这样的 HTML 链接中进行

<a  style=" text-decoration: none;" [routerLink]="['your-path',param1,param2]" target="_blank"  >your label </a>
Run Code Online (Sandbox Code Playgroud)