Hani
Hani

Reputation: 31

routerLink not updating correctly when adding new item to list with ngFor

I have a list of items displayed in my Angular template using the ngFor directive. Each item has a dynamic routerLink directive that generates a link to a specific route. When I add a new item to the list and update the ngFor directive, the routerLink directive on the new item does not work correctly and instead redirects me to the root route (http://localhost:4200/) instead of the expected route (e.g. http://localhost:4200/projects/BB/home). How can I fix this issue?

HTML :

    <ng-container *ngFor="let project of projects">
      <div class="nav-item" routerLinkActive="active">
        <div class="link" [routerLink]="'projects/' + project.code + '/home'">
          <span class="nav-label">{{ project.code }}</span>
        </div>
      </div>
    </ng-container>

Projects list is update after create new project and refetch projects, HTML also is update but routerLink of new project not work correctly

If i create new project where code = 'BB'. on this project click i expect app to redirect me to http://localhost:4200/projects/BB/home instead of http://localhost:4200/

Upvotes: 0

Views: 121

Answers (3)

Hani
Hani

Reputation: 31

Finally i fixed this issue by using ngForTrackBy directive to specify a track-by function for the ngFor directive. This function is used to identify items in the list and can help Angular's change detection mechanism to determine when the list has changed and the routerLink directive needs to be updated.

Here's an example of how i used the ngForTrackBy directive to fix this issue:

HTML :

<div *ngFor="let item of items; trackBy: trackByFn">
  <a [routerLink]="'projects/' + item.code + '/home'">{{ item.name }}</a>
</div>

TS:

trackByFn(index: number, item: any) {
    return item.code; // i use the `code` property as the unique identifier for each item
  }

Upvotes: 0

Syed Khizaruddin
Syed Khizaruddin

Reputation: 435

Replace your [routerLink]="'projects/' + project.code + '/home'" with [routerLink]="['projects/', project.code, '/home']

as below,

<ng-container *ngFor="let project of projects">
  <div class="nav-item" routerLinkActive="active">
    <div class="link" [routerLink]="['projects/', project.code, '/home']">
      <span class="nav-label">{{ project.code }}</span>
    </div>
  </div>
</ng-container>

Upvotes: 0

hasnaas
hasnaas

Reputation: 86

try starting your links with a slash, ie [routerLink]="'/projects/' + project.code + '/home'"

Upvotes: 0

Related Questions