Search code examples
angularngforangularjs-track-by

ngFor trackBy is not identifying items correctly using ngModel


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


Solution

  • 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