ngFor trackBy is not identifying items correctly using ngModel

189 views Asked by At

I will be brief.

Here's the problem on stackblitz: trackByBugntfree\

Explanation:
Resources contain ppermission that are displayed on screen with checkboxes.\

Objective:
When a "permission" is checked, only its referenced object should be modified by using ngModel.\

Issue:
When permission "one" of resource "A" is checked, permission "one" of resource "B" and "C" too.

Edit: Maybe slice is the problem, I will try to fix that

2

There are 2 answers

0
Chellappan வ On BEST ANSWER

Since slice returns shallow copy, It's modifing all the value when we change the value in input.try to do deep copy using JSON.parse(JSON.stringify(this.permissions))

 resources = [
    { resourceId: 1, name: 'One', permissions: JSON.parse(JSON.stringify(this.permissions)) },
    { resourceId: 2, name: 'Two', permissions: JSON.parse(JSON.stringify(this.permissions))},
    { resourceId: 3, name: 'Three', permissions: JSON.parse(JSON.stringify(this.permissions))}
  ];

Forked Example

1
George Koval. On

you need to return permission.id in the trackby (trackby expects a unique identifier), otherwise it won't work

UPD: but your problem is not related to trackby. For all resources you're trying to reference the same array of permissions, so angular treats them as the same. There're different possible solutions, but the most obvious one is to have a permissions property inside each of resources, so that all permissions would have different references.