Search code examples
angularangular-router

Angular 10 - Does Angular have a way to build paths of routes for you?


You can attach data to a route like this:

// app-routing.module.ts
const routes: Routes = [
  {path: "/some/path/bla/", component: SomeComponent, data:{ name: "home1"}},  
  {path: "/some/path/:variable/bla/", component: SomeComponent, data:{ name: "home2"}},
]

Does Angular's Router module have an in-built way to generate the path for you from that data, such as this:

const routeName1 = "home1";
getPathForRoute(routeName1) //Returns "/some/path/bla/"

const routeName2 = "home2";
const parameters = {"variable": "stringValueForVariable"};
getPathForRoute(routeName2, parameters); //Returns "/some/path/stringValueForVariable/bla/"

This is purely to avoid hard-coding paths/routes, similar to how you can do so in Django with its reverse function. I'm aware that the default suggestion seems to be to just throw your routes in a module full of constants and refer to that instead. However, that seems like an unclean solution to me given that you need to maintain that constants file.

This concept seems easy to implement and given that I know there are a lot of smart people working on this, I am almost certain this functionality is in there somewhere and I just don't recognize it. However, skimming through angular's routing documentation, nothing stands out to be Angular's version of this kind of functionality. SO-Questions about avoiding hard-coding routes mostly get answered with aforementioned solution of having a constants-file to store the urls in, which I'd like to avoid for the mentioned reasons. So what am I missing?

Edit: I have accepted that apparently Angular doesn't have anything for this. As such, if anyone wants to go about implementing it themselves, here is what I did so far if you want inspiration (and by the time you're reading this hopefully with a code-review below it to improve whatever I implemented): https://codereview.stackexchange.com/questions/253189/implementing-djangos-reverse-functionality-in-angular-routing


Solution

  • As per my knowledge, Angular Router module doesn't have any in-built way to generate the path. you have to declare the path in routing modules and in code you can use the below code to redirect to the particular page

    this.router.navigate(['/custompath']);