Function is getting called many times by using template interpolation?
Asked Answered
E

1

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.

Estheresthesia answered 17/10, 2016 at 7:19 Comment(1)
Each time when change detection happens, it evaluates binding which is getVal()Porphyroid
D
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.

Dispraise answered 17/10, 2016 at 7:25 Comment(2)
in my project also construtor and other methods are calling 4times. i tried ChangeDetectionStrategy but it is not working.Hess
Sorry, but that's not enough information. I'd suggest you create a new question ideally with a Plunker that reptoduces the issue.Ineligible

© 2022 - 2024 — McMap. All rights reserved.