FullStackDeveloper
FullStackDeveloper

Reputation: 968

Why I need to add '/' to routerLink but we do not have '/' in router definination?

I am following angular official tutorial. This question confused me, but this tutorial did not explain why so.

When we click a element, we route to a view/template. You can see, we have '/heroes', why we need to add '/' in here? I removed the '/', then the router cannot work.

template: `
   <h1>{{title}}</h1>
   <nav>
     <a routerLink="/dashboard">Dashboard</a>
     <a routerLink="/heroes">Heroes</a>
   </nav>
   <router-outlet></router-outlet>

Here is the router definition, but it does not have '/'.

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard',  component: DashboardComponent },
  { path: 'detail/:id', component: HeroDetailComponent },
  { path: 'heroes',     component: HeroesComponent }
];

Upvotes: 0

Views: 182

Answers (1)

Aer0
Aer0

Reputation: 3907

Assuming you're using <a routerLink="/heroes">Heroes</a> Angular would try to route to yoururl/heroes. Using <a routerLink="heroes">Heroes</a> instead appends the link to your current route.

Let's say e.g. you're on this route yoururl/dasboard.

This would basically navigate to yoururl/heroes

<a routerLink="/heroes">Heroes</a>

While this would navigate to yoururl/dasboard/heroes

<a routerLink="heroes">Heroes</a>

Upvotes: 1

Related Questions