Search code examples
javascriptangularperformancetypescriptangular2-changedetection

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

*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

    objectKeys = Object.keys

  2. Use getter method which will return 'Object.keys' ref

    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. So, which way is better to achieve this? Is using first approach having any performance improvement over the second one?


Solution

  • You can use the keyValue pipe which supports change detection. So it will only be executed when the input value is changed.

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

    Documentation: 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.

    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) : [];
        }
    }