Search code examples
typescriptangularangular2-router

Prevent the duplciate path/route usage in the routerLink


Thats my html file:

  <a [routerLink]="['tests/...']">Tests</a>

This terminal route is already defined the parent component Routes configuration.

Due to maintaining my software I would like to declare kind of a constant string and re-use it from my Routes and routerLink.

How can I do that ?


Solution

  • You can't directly access constants from the template of a component.

    You can inject a service that provides access to your "global" values like

    @Injectable() 
    export class RoutePaths {
      test:string = 'tests/...';
      other:string = 'other';
    }
    
    @Component({
      selector: 'some-comp',
      template: `
    <a [routerLink]="[routePaths.test]">Tests</a>
    <a [routerLink]="[routePaths.other]">Tests</a>
    `})
    export class SomeComponent {
      constructor(private routePaths:RoutePaths) {}
    }
    
    bootstrap(AppComponent, [RoutePaths]);