Gopu V
Gopu V

Reputation: 99

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.

Upvotes: 3

Views: 1506

Answers (1)

BhargavG
BhargavG

Reputation: 906

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.

Upvotes: 3

Related Questions