2

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.

Sumit Chaudhari
  • 210
  • 1
  • 15

2 Answers2

4

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.

Tyler Jennings
  • 8,761
  • 2
  • 44
  • 39
1

Create a pipe that converts spaces to hyphens.

@Pipe({
  name: 'kebabCase'
})
export class KebabCasePipe implements PipeTransform {

  transform(value: string): string {
      return value.replace(' ', '-');
  }

} 

Use the pipe in your links:

<a *ngFor="let demo of demos" [routerLink]="['demo', demo.name | kebabCase]">example</a>
Martin
  • 15,820
  • 4
  • 47
  • 56