How to open a new tab with router.navigate in TypeScript

85.4k views Asked by At

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)

6

There are 6 answers

1
Thaadikkaaran On BEST ANSWER

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); 
}
0
Amir dhib On

this.router.navigate([]).then((result) => {
  window.open(url, '_blank');
});

0
MNF On

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>
2
Kamil Kiełczewski On

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');
}
2
harmonickey On

this is my solution

const url = this.router.serializeUrl(this.router.createUrlTree(['/my/url/route'], { queryParams: { ...anyQueryParamsYouWantOrOmitThis } }));
window.open(url, '_blank');
0
Hamidreza Vakilian On

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');
}