mardi 1 août 2023

How to update/render a list of checkboxes with changing list in Angular

I want to display multiple checkboxes using ngFor, as I get the information if the checkbox is checked from the backend. I saw an unexpected behavior and I am not sure how to solve this problem.

The problem is: When I select a checkbox and the backend data (the observable) changes, the manually set checkbox moves.

Here is a short demo: https://stackblitz.com/edit/stackblitz-starters-nzhkwd?file=src%2Fmain.ts In the demo, I simulate a transfer of new array values from the backend (toggling the first value in the array (ON/OFF)). The displayed checkboxes are shown and work as expected. But when selecting another checkbox, this selected checkbox "moves".

I tried:

  • ngIf to be sure the array is available
  • added ngAfterViewInit to trigger the detectChanges
  • I changed the ChangeDetectionStrategy to OnPush
  • I inspect in browser the behavior: the id of the changed element would be rendered later...

Do you guys have any idea how I can prevent this behavior?

Sorry for the stupid question, but I'm confused...

Thanks a lot and have a nice day!




Aucun commentaire:

Enregistrer un commentaire