Search code examples
javascriptangularangular2-routingrouterlink

Format routerLink param url


In my angular 2 app I have defined a router link like :

<a *ngFor="let demo of demos" [routerLink]="['demo', demo.name]">example</a>

Currently I am getting demo.name as "example.net/demo/A%20%demo%20%test". I want to format this as "example.net/demo/a-demo-test" to show in the browser address bar.

Any help would be appreciated.


Solution

  • You can use functions inside routerLink. So you can use a function in your component:

      hyphenateUrlParams(str:string){
        return str.replace(' ', '-');
      }
    

    And use it in your routerLink:

    [routerLink]="['/demo', hyphenateUrlParams(demo.name)]"
    

    This provides much more re-usability than mutating variables directly inside the routerLink.