Search code examples
angulartypescriptdynamic-url

How to create dynamic url with logged in username in Angular 8


I have never done this before so that is why i have put this question here and need an explanation or an example blog that can tell me exactly how i can create a dynamic url like this demo.com/username. Currently my routes are working like this demo.com/settings/emailsettings but i need to implement the logic that it becomes demo.com/username/settings/emailsettings.

Note: The above urls are just for example and they are not real.


Solution

  • in your routes you need to define a param

    {
      path: '/:username/settings/emailsettings',
      component: YourComponent
    }
    

    Then, when navigate by code you will pass the username to the route dynamically.

    From component class:

    this.navigate([user.username, 'settings', 'emailsettings'];
    

    From component template

    [routerLink]="[user.username, 'settings', 'emailsettings']"