0

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.

1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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 { }

2 Comments

Perfect, minimally intrusive solution. This resolves the problem with Azure hosted Angular routes which contain a dot character in their route parameters that break when a refresh is requested. Azure gets confused by a url which contains a dot followed by some alphanumeric characters, unless there is a trailing slash at the end of the path.
I would slightly improve the code by changing the line to url = url.length > 1 && !url.endsWith('/') ? url += '/' : url;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.