Blog>
Snippets

Avoid Function Calls in Templates

Prevent performance issues by avoiding function calls inside templates and use property bindings or pipes instead.
// Component class

class MyComponent {
  // Instead of using a function to calculate a value in the template
  // We use a property
  value: string;

  constructor() {
    // Calculate value when initializing or when the data changes
    this.value = this.calculateValue();
  }

  calculateValue() {
    // Perform the calculation
    return 'Calculated Value';
  }
}

// Usage in a template:
// <div>{{ myComponent.value }}</div>
This example demonstrates the use of a component property instead of a function call within a template to avoid performance penalties of such function calls during change detection cycles.
// Angular Pipe

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

@Pipe({
  name: 'calculateValuePipe'
})
export class CalculateValuePipe implements PipeTransform {
  transform(input: any): any {
    // Perform the calculation or transformation
    return 'Calculated Value Based on ' + input;
  }
}

// Usage in a template:
// <div>{{ inputData | calculateValuePipe }}</div>
This code defines an Angular pipe that encapsulates the function call, allowing it to be used within a template without being called directly, thus optimizing performance.