function gets called several times

Viewed 11504

I want to display a dataList. Some values are calculate from a function. It seems angular2 calls the calculate function many times.

  <tr *ngFor="let data of dataList">
    <td>{{ data.no }}</td>
    <td>{{ data.name }}</td>
    <td>{{ calculateFunction(data.price) }}</td>
  </tr>

Console will output "calculate..." many times, more than dataList.length.

calculateFunction() {
  console.log('calculate...');
  return ...;
}

Should I worry about that for performance or just let angular2 do this?

3 Answers

you can change the components changeDetectionStrategy to onPush. after that, your calculateFunction function does not call several times.

to do that :

in your component:

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css'],
 changeDetection: ChangeDetectionStrategy.OnPush // this line
})

export class AppComponent {

  ....

  calculateFunction(value) {
    console.log('calculate...');
    return ...;
  }
}

and in your app.component.html :

 <tr *ngFor="let data of dataList">
  <td>{{ data.no }}</td>
  <td>{{ data.name }}</td>
  <td>{{ calculateFunction(data.price) }}</td>
 </tr>

UPDATED

The best way to handle this scenario is to use Pipe, like the following :

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'handlePrice'
})
export class HandlePricePipe implements PipeTransform {
  transform(price: number): number {
    console.log('In Pipe ....');
    return price * 2;
  }
}

Then use that :

<tr *ngFor="let data of dataList">
   <td>{{ data.no }}</td>
   <td>{{ data.name }}</td>
   <td>{{ data.price |handlePrice }}</td>
</tr>
@Component({
.
.
 changeDetection: ChangeDetectionStrategy.OnPush // this line
})
export class MyComponent {
}

adding change detection to the component decorator solved the issue for me.

Related