Angular trackBy not working in nested *ngFor

2.4k views Asked by At

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.

1

There are 1 answers

3
Sunil Singh On

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.
  }