Search code examples
angularangular-routingangular-router

angular routerlink with '&' in route parameter value


Hi I'm having an issue where due to the fact I have a route param that contains a '&' character in it. Here is my route config:

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full'},
  {path: 'home', component: HomeComponent},
  {path: 'work', component: WorkComponent},
  {path: 'who', component: WhoComponent},
  {path: 'process', component: ProcessComponent},
  {path: 'services', component: ServicesComponent},
  {path: 'project/:name', component: ProjectComponent}
];

Here is my link:

<button class="some-class" [routerLink]="'/project/R&D more text here'">R&D Things and stuff</button>

The first time the link is clicked everything works great, the correct route is activated and the name route param gets the full string value. The issue is on a page refresh the router is changing the url to:

http://localhost:4200/project/R

Whats the best way to handle this routing issue?


Solution

  • You can use encodeURIComponent("R&D some other text here") to encode this properly.

    So create a property in your Component:

    url = `/project/${encodeURIComponent('R&D Some Other Text')}`;
    

    And then in your template:

    <button class="some-class" [routerLink]="url">R&D Things and stuff</button>
    

    When you want to capture the name property of the route param, you can use ActivatedRoute, and then use decodeURIComponent to decode the name:

    constructor(private route: ActivatedRoute) {}
    ...
    ngOnInit() {
      this.route.params
        .subscribe(params => {
          const name = decodeURIComponent(params['name']);
          console.log(name);
          ...
        });
      ...
    }
    

    Here's a Working StackBlitz for your ref.