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

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

问题描述

在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中的值

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

建议在表达式中调用组件方法吗?或者,如果我使用totalSqft来显示计算

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

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

这里的问题是,当以下表单元素totalLengthtotalBreadthtotalheightmylocalVar的值更改时,如果totalSqft是我如何调用myMethod()?

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天全站免登陆