Danielle
Danielle

Reputation: 3839

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

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)

Upvotes: 34

Views: 95139

Answers (6)

Hamidreza Vakilian
Hamidreza Vakilian

Reputation: 860

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

Upvotes: 0

Amir dhib
Amir dhib

Reputation: 39

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

Upvotes: 3

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92347

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

Upvotes: 28

harmonickey
harmonickey

Reputation: 1419

this is my solution

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

Upvotes: 57

MNF
MNF

Reputation: 717

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>

Upvotes: 4

Thaadikkaaran
Thaadikkaaran

Reputation: 5226

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

Upvotes: 13

Related Questions