5

Sorry for basic question, I am trying to understand the angular2 flow using basic example.

import { Component } from '@angular/core';

@Component({
    selector:'my-app',
    template:'Test {{ getVal() }}'
})

export class AppComponent{ 
    getVal():void{
        console.log("demo text")
    }
}

After running this example, "demo text" is visible in console 4times, why is it so ? Thanks.

kirodge
  • 676
  • 5
  • 23
wmnitin
  • 3,387
  • 1
  • 13
  • 19

1 Answers1

9

Binding to functions or methods in the template is discouraged because these functions are called every time change detection is run.

You should at least cache results inside the function to avoid repeatedly recalculating potential expensive calculations.

A better approach is to recalculate the result when properties change the result depends on, and assign the result to a property and bind to this property from the view instead.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • in my project also construtor and other methods are calling 4times. i tried ChangeDetectionStrategy but it is not working. – Nunna Suma Apr 11 '17 at 04:41
  • 1
    Sorry, but that's not enough information. I'd suggest you create a new question ideally with a Plunker that reptoduces the issue. – Günter Zöchbauer Apr 11 '17 at 04:57