Shubham Sharma
Shubham Sharma

Reputation: 315

Angular trackBy not working in nested *ngFor

My component is some what like

<div class="users-list" *ngIf="datasetPermission !== undefined">
    <div *ngFor="let userpermission of datasetPermission; trackBy : trackByFn">
      <span *ngFor="let user of userpermission.users">
        <span *ngIf="user">
        <span class="shared-user"><span>{{user.emailId}}</span><span ><span  class="close icon-key" style=" padding: 0;" (click)="viewPermission($event,userpermission.permissionType,user)"></span><span class="close" style=" padding: 0;" (click)="removeUser(user)">×</span></span></span>
      </span>
      </span>
    </div>
  </div>

trackBy function as

    public trackByFn(index, userpermission) {
      console.log(userpermission.permissionType);
      return userpermission.permissionType;
    }

Inside permissions I've array of users who are assigned to this permission.I can update users from x <> y permission set. when I'm updating the datasetPermission array or adding new element to it it is updating the order of dataset being updated/added.

I've gone through various posts but yet to find something useful. Am I doing something incorrect here? Any help would be appreciated.

Upvotes: 5

Views: 2584

Answers (1)

Sunil
Sunil

Reputation: 11243

There is wrong implementation for trackByFn.

trackBy function always accept two parameters index and current item and function must return the unique identifier.

So your function should be like -

public trackByFn(index, userpermission) {
    return userpermission.id; //check what unique property you have in permission class.
  }

Upvotes: 2

Related Questions