是否建议在模板表达式中调用方法? [英] Is it advisable to call a method in a template expression?

查看:23
本文介绍了是否建议在模板表达式中调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Angular 2 中,是否建议在表达式中使用组件方法?例如,我有以下组件

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;
    }
}

我像这样在 area-component.html 中显示值

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

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

在表达式中调用组件方法是否可取?或者,如果我使用 totalSqft 来显示计算

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

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

这里的问题是,如果 totalSqft 是我调用 myMethod() 的方式,而以下表单元素的值发生变化 totalLength, totalBreadth, totalheight, mylocalVar?

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 ?

推荐答案

明确不鼓励直接绑定到方法,因为它会导致几个问题.

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

  • 每次Angular2运行变化检测时都会调用该方法.如果该方法执行一些计算密集型工作,则可能会使您的应用程序无响应.

  • 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.

这篇关于是否建议在模板表达式中调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆