Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 360
Danielle Avatar asked Jan 08 '17 09:01

Danielle


People also ask

Can I use routerLink on Div?

Yes it can be attached to div tag, your route is probably wrong try add / in front of route.

Can we add routerLink to button?

Using Router linksAfter Angular v4 we can directly add a routerLink attribute on the anchor tag or button.

How does Angular router navigate work?

Angular router traverses the URL tree and matches the URL segments against the paths configured in the router configuration. If a URL segment matches the path of a route, the route's child routes are matched against the remaining URL segments until all URL segments are matched.


2 Answers

this is my solution

const url = this.router.serializeUrl(this.router.createUrlTree(['/my/url/route'], { queryParams: { ...anyQueryParamsYouWantOrOmitThis } }));
window.open(url, '_blank');
like image 168
harmonickey Avatar answered Sep 21 '22 15:09

harmonickey


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');
}
like image 38
Kamil Kiełczewski Avatar answered Sep 18 '22 15:09

Kamil Kiełczewski