Retrieving the base HREF in Angular to construct a URL for opening in a new window - dialloi659/angular GitHub Wiki

import { Component, Inject } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(@Inject(APP_BASE_HREF) public baseHref: string) {  }
  public openNewWindow= (id: string) => {
    const route = `users/details/${id}`;
    const baseUrl = window.location.origin;
    const baseHref = this.baseHref || '/';
    const url = `${baseUrl}${baseHref.endsWith('/') ? baseHref : baseHref + '/'}${route}`;
    window.open(url, '_blank');
  }
}

Provider config

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [
    {
      provide: APP_BASE_HREF,
      useFactory: (s: PlatformLocation) => s.getBaseHrefFromDOM(),
      deps: [PlatformLocation]
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}