Recently I found an awesome library that allows for React components to be used in Angular applications, called ngReact
My question is about the watch-depth attribute that can be declared on a reactDirective component:
<body ng-app="app">
<div ng-controller="helloController">
<hello-component watch-depth="reference" fname="person.fname" lname="person.lname"></hello-component>
</div>
</body>
Looking at ngReact documentation for the reactDirective service I see that there are 3 possible values for watch-depth:
In my initial exploration using ngReact I have been sticking with using the default value option.
My question is, what are the differences between these types?
Simple examples for when each watch-depth type is ideal to use would be great!
The answer has to do with how angular's $watch works. There are 3 ways angular applies $watch: Reference, Collection, Value (as you've already mentioned).
Reference:
Reference looks at the reference of a value and will only register a change (and cause a rerender) if that reference changes. This is the least expensive watch type. example of a reference change:
$scope.userArray = newUserArray
Collection:
A watch-depth of Collection is more in depth. It will look inside the collection. It will register a change if a Watch By Reference would have fired, or if a new item is added, removed, or reordered within the collection.
$scope.userArray.push(newUser);
Value:
A watch-depth of value is the most expensive. It will watch the values within a collection. It will register a change if Watch By Reference would have fired, if Watch By Collection would have fired, or if a value within the collection changes.
$scope.userArray[0].age = 32;
This answer was heavily inspired by an excellent article written by Tero Parviainen, https://teropa.info/blog/2014/01/26/the-three-watch-depths-of-angularjs.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With