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

吃可爱长大的小学妹 提交于 2019-12-13 22:17:22

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/41284000/is-it-advisable-to-call-a-method-in-a-template-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!