0
<ul>
<li *ngFor=let choice of checkboxlist.options>

<mat-checkbox [checked]=isChecked(choice) > <mat-checkbox>
<li>
<ul>

in ts file I have function for isChecked based on some logic it returns true or false (this works fine) but the functions is get triggering multiple times.

Veera
  • 101
  • 1
  • 4

1 Answers1

1

Is the function getting triggered once for each option in your checkboxlist.options?

When you update a single selection in your checkboxlist.options list, and it is re-rendering the whole DOM for each <li *ngFor, you can help it be a little smarter.

For small applications where your looping over a handful of options this is not a big deal. However, it is good practice and if your list is large then you want to use trackBy in your ngFor

If you use trackBy then your list will ONLY update the list items that are changed.

There's a lot of references out there that will help you build your trackBy method better than I will, here is a good starting point for another StackOverflow question about it.

Good luck!

MindlessRouse
  • 425
  • 2
  • 12
  • yes the function is getting triggered for each option, even adding the TrackBy did not resolve the issue not sure what is the root cause for it @MindlessRouse – Veera Mar 25 '22 at 16:56
  • It's likely because youre looping over an array of native objects `[false, false, true]` instead of an object `[{id:1, value: false},{id:2, value: false},{id:3, value: true}]`. If you want trackby to do its thing, you would need something like that last one. All this to say, if it is just a few checkboxes on the page, is there a performance issue with rendering them all on every click? – MindlessRouse Mar 25 '22 at 18:33
  • What does "choice" and "isChecked" look like? – MindlessRouse Mar 25 '22 at 18:34
  • @ MindlessRouse choice object [ {name: 'ABC', value: false, actualValue:'1'} , {name: 'xyz' value: false, actualValue:'2'} ] icChecked(field:string, value:string):boolean{ // Some Logic return True or False } – Veera Mar 28 '22 at 04:52