[Fixed] Angular 6 routerLink on a new tab

Issue

I’m trying to open a routerlink on a new tab instead of on the current page but regular html attributes like target _blank are not working.

<span routerLink="/custompage/{{city.id}}"  class="badge badge-primary badge-pill">open</span>

Solution

Here’s an alternate way of doing within a component.

openCityInNewWindow(city) {
  // Converts the route into a string that can be used 
  // with the window.open() function
  const url = this.router.serializeUrl(
    this.router.createUrlTree([`/custompage/${city.id}`])
  );

  window.open(url, '_blank');
}

Html will look something like

<ul *ngFor="let city of cities">
  <li (click)="openCityInNewWindow(city.id)">{{city.name}}</li>
</ul>

Leave a Reply

(*) Required, Your email will not be published