Home > Enterprise >  is using array.inclues in templare a performance issue in angular
is using array.inclues in templare a performance issue in angular

Time:01-11

my component have changeDetection:  ChangeDetectionStrategy.OnPush and component have a array variable

myids:Array<number>;


addId(id:number){
 this.myids.push(id)
}

in the template I am using:

 <div [class.active]="myids.includes(step.id)"></div>

My question, is it a performance problem to use myids.includes in template ?

CodePudding user response:

Yes, it's very likely looping over the array on every change detection cycle

Whenever you add an id via addId, you could update a class property e.g. this.isActive = myids.includes(step.id), and use the isActive property in the html

CodePudding user response:

I'm not pretty shure if it is a performance problem. BUT: You should seperate html templates which are responsible for viewwing and the code of your component which are responsible to react of events and bring the model to the view. The core concept of that is Model-View-Controller. (MVC)

I recommend to calculate your "active" property in the controller or a service.

Do it like this:


public class MyComponent {

   public isActive: boolean;
   private myIds: string[];

   constructor() {
      this.isActive = false;
      this.myIds = [];

   }

   public ngOnInit(): void {
      // load myIds
     // this.myIds = this._myIdsService.getIds();
    this.isActive = this._myids.includes(step.id);

   }

}

And then bind this property to your view...

 <div [class.active]="isActive"></div>
  • Related