Search code examples
angularangular-lifecycle-hooks

How to stop multi trigger of functions in angular when using functions in template?


I am using a function inside HTML template, I cannot use a variable directly because the condition is little complex.

My Problem is that the function in the template is called multiple times.

For Example this Stackblitz (Minimal, Reproducible Example)

Logs get Name was called 4 times on load and 2 more times after clicking Change Version button.

I would like to call this once on load and only one per click. How can I achieve that for performance's sake


Solution

  • Set the changeDetection mode of the component to OnPush

    https://angular.io/api/core/ChangeDetectionStrategy

    Using OnPush will tell Angular to only render the template when the @Input() bindings for the component has changed. The default mode will perform change detection for the template on each digest cycle, and since the expression is using a function it has to call it every time to see if the value has changed.

    @Component({
      selector: 'hello',
      template: `<h1>Hello {{getName()}}!</h1>
      <button (click)="changeName()"> this</button>`,
      styles: [`h1 { font-family: Lato; }`],
      changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class HelloComponent implements OnInit{
       // ....
    }
    

    Here's a blog on the topic:

    https://netbasal.com/a-comprehensive-guide-to-angular-onpush-change-detection-strategy-5bac493074a4