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?

1

There are 1 best solutions below

0
On

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)
}