Sathya V
Sathya V

Reputation: 629

Is it advisable to call a method in a template expression?

In Angular 2 is it advisable to use a component method in an expression? For example, I have the following component

  export class AreaComponent {

    totalLength: number;
    totalBreadth: number;
    totalheight: number;
    mylocalVar: number;

    totalSqft: number;

    myMethod(): number {
        let totalArea = this.totalLength * this.totalBreadth * this.totalheight;
        let myVar = 0;
        switch (this.mylocalVar) {
            case 0:
                myVar = 8;
                break;
            case 1:
                myVar = 9;
                break;
            case 2:
                myVar = 10;
                break;
        }

        this.totalSqft = totalArea * myVar ;

        return totalArea * myVar;
    }
}

I am displaying the value in area-component.html like this

<label>{{ myMethod() }}</label>

Is it advisable to call component method in expression? Alternatively if I use totalSqft to display calculation

<label>{{ totalSqft }}</label>

Here problem is if totalSqft is how I call myMethod() while value changes on following form elements totalLength, totalBreadth, totalheight, mylocalVar?

I am using template driven approach.

Is any alternative solution available for this scenario in template driven approach ?

Upvotes: 0

Views: 134

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657781

Binding to methods directly is exlicitly discouraged because it can cause several problems.

  • The method is called every time Angular2 runs change detection. If the method does some compute-intensive work this can make your application unresponsive.

  • If the method returns different results on successive calls (for example an new object instance is returned for every call) change detection throws an error like `Expression has changed after it was checked.

If you are aware of the pitfalls and know how to avoid them, you can use methods in bindings and they will work fine, but because it is so easy to cause troubles it is discouraged in the style guide.

Actually I just tried to find the style guide rule that tells that it's discouraged but couldn't find it.

Upvotes: 2

Related Questions