0

So I have an array structure like so:

const array = [
    {
        key: 'xxx1',
        data: [
           {
               key: 'yyy1',
               //...
               propThatWillChangeOverTime: 'foo'
           },
           //...
        ]
    },
    //...
]

In the html where I print the above array struture, I opted to use two ng-repeat (nested) and, to gain performance, used track by on both of them, something like:

<div ng-repeat="parent in array track by parent.key">
    <div ng-repeat="child in parent.data track by child.key">
        (...)
        <custom-angular-component
            child="child">
        </custom-angular-component>
        (...)
    </div>
</div>

custom-angular-component bindings: child: '='

Now, propThatWillChangeOverTime will (like the name says) change over time, however it never has the value updated. If I remove the first track by, the value updates. However this is something I can't do, as it will have a negative effect on other components.

Is there a way to watch the property I want to "do something with when its value changes"?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Comum
  • 453
  • 5
  • 21
  • can you show us what's going on in that custom angular component? this shouldn't really be problematic the way you have it layed out unless you're doing something interesting in the directive initialization as track by doesn't really relate to change detection so much as it relates to directive instantiation. – bryan60 Dec 20 '19 at 15:42
  • also kind of matters how / why that property is changing – bryan60 Dec 20 '19 at 15:58

1 Answers1

1

Use the $doCheck Life-cycle Hook1

With version 1.5.8, AngularJS added the $doCheck life-cycle hook to the $compile service.

From the Docs:

The controller can provide the following methods that act as life-cycle hooks:

  • $doCheck() - Called on each turn of the digest cycle. Provides an opportunity to detect and act on changes. Any actions that you wish to take in response to the changes that you detect must be invoked from this hook; implementing this has no effect on when $onChanges is called. For example, this hook could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not be detected by Angular's change detector and thus not trigger $onChanges. This hook is invoked with no arguments; if detecting changes, you must store the previous value(s) for comparison to the current values.

-— AngularJS Comprehensive Directive API Reference — Life-cycle hooks

app.component("customAngularComponent", {
  bindings: {
    child: "<"
  },
  controller: function() {
    var oldPropThatWillChange;
    this.$doCheck = () => {
      if (this.child.propThatWillChange !== oldPropThatWillChange) {
        //"do something with when its value changes"
      };
      oldPropThatWillChange = this.child.propThatWillChange;
    };
  }
})
Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95