1

In my UI, I have too many checkboxes arranged in the form of a grid. Their checked status should be determined from the one time logic which is present in the component. Once updated their status are never going to get changed.

I have updated the checked status by calling a function as below.

[checked]="getCheckedStatus()"

Simplified problem is present in this stackblitz - https://stackblitz.com/edit/angular-o622bw?embed=1&file=src/app/app.component.html

Problem - console.log() (or say getCheckedStatus()) gets fired too often whenever Update button is clicked which is slowing down the performance.

Ashwin
  • 12,081
  • 22
  • 83
  • 117

2 Answers2

2

Since getCheckedStatus is called from the template, it will be called each time the Angular change detection is performed.

You could change the changeDetectionStrategy to "onPush" if you want to handle the change detection on your own.

Read more about this here: https://angular.io/api/core/ChangeDetectionStrategy

The example bellow solves the problem:

// ...
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  changeDetection:  ChangeDetectionStrategy.OnPush // <--
})
// ...
TheAngularGuy
  • 939
  • 8
  • 13
  • https://stackblitz.com/edit/angular-o622bw?embed=1&file=src/app/app.component.html Here I have applied onPush strategy and still it is getting called number of times. Any idea why? – Ashwin Aug 30 '19 at 12:51
  • It is called 8 times since you have 8 checkboxes, and each one calls the method once. – TheAngularGuy Aug 30 '19 at 12:53
  • Any idea how can I avoid consoling 1000 times? – Ashwin Aug 30 '19 at 12:54
  • 1000? i've tried on multiple browsers and have only 8 (0 to 7). – TheAngularGuy Aug 30 '19 at 12:56
  • My original application has lot many checkboxes. This SB is a scaled down version. – Ashwin Aug 30 '19 at 12:58
  • I see, then you could store the available items (the checked once) in a hashtable, so you would improve your performances quite a lot. And each time you want to know if a checkbox is checked you do `hashtable[itm.id] // if it's checked it returns true`. – TheAngularGuy Aug 30 '19 at 13:02
1

I think that you problem is calling a function from the view. This makes Angular call the function every type it checks the view. So calling function from the view can be a performance problem. If you need to transform thing based on things in the view you can use a pipe. Now it will not be called every time, and is handled by Angular.

I hope it's ok but I took a copy of you stackbliz and made a version using a pipe called selectStatus. [checked]="{accnt:accnt, itm:itm} | selectStatus"

https://stackblitz.com/edit/angular-hzdt4n

Gaotter
  • 1,746
  • 15
  • 32