Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function is getting called many times by using template interpolation?

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.

like image 986
wmnitin Avatar asked Feb 06 '23 22:02

wmnitin


1 Answers

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.

like image 74
Günter Zöchbauer Avatar answered Feb 13 '23 06:02

Günter Zöchbauer