Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RouterLink is not working properly dynamically in angular 6

dashboard.html

<ul class="nav flex-column">
  <li class="nav-item">
    <a class="nav-link" routerLink='/dashboard'>Dashboard</a>
  </li>
  <li class="nav-item" *ngFor="let cat of categories; let i = index">
    <a class="nav-link" [routerLink]="cat.categories">
      <i class="fa fa-{{cat.Icon}}" aria-hidden="true"></i>
      &nbsp;{{cat.categories}}
    </a>
  </li>
</ul>

I am generating a list dynamic, it is just like

<li>Page1</li>
<li>Page2</li>
<li>Page3</li>
<li>Page4</li>

and my current route is "http://localhost:4200/dashboard". Now i want to route when i click on

<a class="nav-link" [routerLink]="cat.categories">
  <i class="fa fa-{{cat.Icon}}" aria-hidden="true"></i>&nbsp; 
  {{cat.categories}}
</a>

the desired route is "http://localhost:4200/dashboard/page1". It works fine when I click the first time, but when I click on another link it gives me the error

core.js:1673 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'dashboard/page1/page2'.

app-routing.module.ts

{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
{ path: 'dashboard/:name', component: DashboardComponent, canActivate: [AuthGuard] }
like image 254
fahad ali Avatar asked Nov 30 '25 10:11

fahad ali


1 Answers

Change your routerLink by prepending /dashboard/:

[routerLink]="'/dashboard/' + cat.categories"

If the first segment begins with /, the router will look up the route from the root of the app.

If the first segment begins with ./, or doesn't begin with a slash, the router will instead look in the children of the current activated route.

And if the first segment begins with ../, the router will go up one level.

like image 59
Poul Kruijt Avatar answered Dec 01 '25 23:12

Poul Kruijt



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!