Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 route navigation with name instead of path

I'm using angular cli version - 1.6.0 These routes i have used.

App.module.ts

const routes: Routes = [
  { path: '', component: AppComponent },
  { path: 'tutorial', component: TutorialComponent },
];

And i used navigation like this

App.component.ts

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

App.component.html

<div class="nav-menu-blocks">
        <a routerLinkActive="w--current" [routerLink]="['/tutorial']" class="nav-link w-nav-link">About</a>
      </div>

These are working good, But i want route navigation with name instead of path or url. I didn't want to include my url for navigation in all components. I just need to set name for my route and want to use that name in all components for route navigation.

Is this possible to use like that? Can anyone help to solve this? Thanks in advance.

like image 356
Gopu V Avatar asked Dec 20 '25 07:12

Gopu V


1 Answers

As far as I understand you want to use name rather than direct path. You can do that by making a Route.ts file.

For example -

// route.ts file
export class Route {
public static TUTORIAL = 'tutorial';
}

and use that file wherever you want to use it.

this.router.navigate(['/' + Route.TUTORIAL]);

<div class="nav-menu-blocks">
    <a routerLinkActive="w--current" [routerLink]="tutorialUrl" class="nav-link w-nav-link">About</a>
  </div>

// TS file
get tutorialUrl() {
return ['/' + Route.TUTORIAL];
}

The good thing about this approach is that in future if you want to change that path, you don't need to change it everywhere. Just need to change it in the Route file.

Hope this helps.

like image 75
BhargavG Avatar answered Dec 22 '25 00:12

BhargavG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!