简体   繁体   English

在angular6模板中使用getter方法或类变量?

[英]Use of getter method or class variable inside angular6 template?

I want to call Object.keys method inside the html of angular component to check if the object is empty or not 我想在角度组件的html内调用Object.keys方法,以检查对象是否为空

*ngIf = "Object.keys(dataToBeChecked).length === 0"

As 'Object' is not accessible inside the template, we can achieve this in two ways. 由于无法在模板内部访问“对象”,因此我们可以通过两种方式实现此目的。

  1. Declare class variable with a value as 'Object.keys' function ref 将类变量声明为'Object.keys'函数引用

    objectKeys = Object.keys objectKeys = Object.keys

  2. Use getter method which will return 'Object.keys' ref 使用getter方法将返回“ Object.keys”引用

    get objectKeys() { return Object.keys; get objectKeys(){return Object.keys; } }

Final code is 最终代码是

*ngIf = "objectKeys(dataToBeChecked).length === 0"

I know that, even if I use either approach, the function will be called multiple times by the change detection system of angular to know the evaluation status. 我知道,即使我使用任何一种方法,角度的变化检测系统都会多次调用该函数以了解评估状态。 Second approach does two method calls frequently, one to get the Object.keys ref and another to evaluate Object.keys. 第二种方法经常执行两种方法调用,一种方法是获取Object.keys引用,另一种方法是评估Object.keys。 So, which way is better to achieve this? 那么,哪种方法更好地实现这一目标? Is using first approach having any performance improvement over the second one? 使用第一种方法是否比第二种方法有任何性能改进?

You can use the keyValue pipe which supports change detection. 您可以使用支持更改检测的keyValue管道。 So it will only be executed when the input value is changed. 因此,仅当输入值更改时才执行。

*ngIf = "(dataToBeChecked | keyValue).length === 0"

Documentation: https://angular.io/api/common/KeyValuePipe 文档: https : //angular.io/api/common/KeyValuePipe

Updated: 更新:

As pointed out in the comments. 正如评论中指出的那样。 The keyValue pipe is not pure which means that it's executed even if the value has not changed. keyValue管道不是纯管道,这意味着即使值未更改也已执行。

You can use this custom pipe instead. 您可以改用此自定义管道。

@Pipe({name: 'objectKeys', pure: true})
export class ObjectKeysPipe implements PipeTransform {
    public transform(value: any): any {
        return typeof value === 'object' ? Object.keys(value) : [];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM