2

I have a variable user_roles in my component file which gets initialized by an API on ngInit() and does not change after that.

this.service.getUserRoles().subscribe(
      data => {
        this.user_roles = data;
      }
    )

user_roles is an array which contains the permissions for that user : user_roles = ['admin', 'mediator', ...]

In my template I have code that displays components based on user_role:

<div *ngIf="user_roles.includes('admins') || user_roles.includes('mediator')">

    <div ....
    .
    . 
    .

Does .includes() run every time some other variable changes and the change detection loop runs? If it does, then what alternative can I use to improve performance?

Shashank Ks
  • 450
  • 5
  • 9
  • One way to see it by yourself is to create a getter in the Typescript which does a `console.log` and use it instead of the direct variable in the template – Gaël J Jun 20 '21 at 06:48
  • Also one way to optimize is to compute the condition only once and store the result in a variable. I'm not convinced it will have that big of an impact in your example though. – Gaël J Jun 20 '21 at 06:49

1 Answers1

1

Yes it will.

angular change detection doesn't mean if a property changes, update its dependencies. That's actually the vue way. In reality angular change detection means everytime a async action(Promise event setTimout) happens, re-evaluate every template binding. So yes, includes will be called again.

The simplest way to verify is following

const orig = Array.prototype.includes
Array.prototype.includes = function<T> (arg: T) {
    console.log(this, arg)
    orig.call(this, arg)
}
Austaras
  • 901
  • 8
  • 24