Mohammed Sabbah
Mohammed Sabbah

Reputation: 883

Angular 2 url parameters

How I can add trailing slash to the end of url for specific component? (My client requires it, so no need to add a comment saying; don't use trailing slash).

Thanks in advance.

Upvotes: 0

Views: 710

Answers (2)

Fredrik Lundin Grande
Fredrik Lundin Grande

Reputation: 8186

You can try to implement a custom UrlSerializer. It could look something like this:

import { DefaultUrlSerializer, UrlTree } from '@angular/router';

export class CustomUrlSerializer extends DefaultUrlSerializer  {
    parse(url: string): UrlTree {
        return super.parse(url);
    }

    serialize(tree: UrlTree): string {
        let url = super.serialize(tree);
        url = url.length > 1 ? url += '/' : url;

        return url;
    }
}

Then provide it in your NgModule:

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [...
                {provide: UrlSerializer, useClass: CustomUrlSerializer}
              ],
  bootstrap: [...]
})
export class AppModule { }

Upvotes: 1

Teddy Sterne
Teddy Sterne

Reputation: 14221

You can achieve the desired result by defining your routes with a trailing slash and then making sure to navigate to the url with the slash. It will most likely result in a few headaches because the router will be one level deeper than you would expect because of the trailing slash.

Routes
{
    path: 'a/',
    component: AComponent
},
{
    path: 'list/b/',
    component: BComponent,
}

You can get the router to add the trailing slash by adding an empty string path after the defined route. If you write the slash yourself, like [routerLink]="['/a/']" angular will remove it.

Link
<p><a [routerLink]="['/a', '']">Component A</a></p>

or

<p><a [routerLink]="['../a', '']">Component A</a></p>
Programatically Navigate
this.router.navigate(['/a', '']);

Demo

Upvotes: 2

Related Questions