27

The following typescript code will always open in the current browser tab

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

How do I make router.navigate open in a new tab ? (that is when $event.ctrlKey is true)

Arman Fatahi
  • 2,635
  • 3
  • 24
  • 37
Danielle
  • 3,324
  • 2
  • 18
  • 31

6 Answers6

46

this is my solution

const url = this.router.serializeUrl(this.router.createUrlTree(['/my/url/route'], { queryParams: { ...anyQueryParamsYouWantOrOmitThis } }));
window.open(url, '_blank');
harmonickey
  • 1,299
  • 2
  • 21
  • 35
  • Isn't this an Angular answer? – xr280xr Nov 23 '21 at 23:41
  • Makes sense, to me, anyway. If you type "router.navigate" into Google search, about 98% of the returned matches are about Angular. – StackOverflowUser May 11 '22 at 07:49
  • Admittedly I didn't see the tags on the question and just assumed they were asking about Angular based on the context of the code. Clearly it's talking about the knockout.js framework called Durandal which uses similar syntax for route navigation, hence my confusion. https://www.infoq.com/articles/durandal-javascript-framework/ – harmonickey May 17 '22 at 20:51
20

This one works with # hash (like https://example.com/#/users) and non-hash urls

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

    window.open(baseUrl + newRelativeUrl, '_blank');
}
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
13

Yes, as you @Daneille commented, you have to handle by your own way since durandal's router plugin (navigate function) does not provide a way to open a new tab.

So it is better to handle something as you commented.

if ($event.ctrlKey) { 
    window.open(url); 
}
Thaadikkaaran
  • 5,088
  • 7
  • 37
  • 59
  • 1
    How do I retrieve url from the Router at least? What if somebody changes routes configuration afterwards? – Gherman Nov 16 '17 at 16:23
4

I think it is better to do in HTML link like this

<a  style=" text-decoration: none;" [routerLink]="['your-path',param1,param2]" target="_blank"  >your label </a>
MNF
  • 687
  • 9
  • 13
2

this.router.navigate([]).then((result) => {
  window.open(url, '_blank');
});
aaossa
  • 3,763
  • 2
  • 21
  • 34
Amir dhib
  • 29
  • 3
0

Use this method as a replacement for router.navigate(...) for a new window:

navigateNewWindow(router: Router, commands: any[]) {
    let baseUrl = window.location.href.replace(router.url, '');
    const url = new URL(commands.join("/"), baseUrl).href
    window.open(url, '_blank');
}