The Angular feature $watch has become known for its tendancy to hog memory, so we’ve been avoiding it wherever we can. However, with Components, the fact that you may only have a few bound values makes it much more necessary to have a watch on a value. There is a very easy way to do this.
Angular Components contain several hooks that are very handy. The $onChanges is especially powerful. In this example, I have a dropdown menu that I’d like to populate from a database API. The dropdown is always dependent on the office_id, so one of our bindings is officeId. However, if the user on the parent form changes the value of officeId from their own dropdown of offices, I need to reload the array of clients.
The key was trying to figure out how to capture the change. Here, I’ve stripped out the HTML and just given an example of the usage of $onChanges in a typescript file.
module Application.Components.Client { export class clientSelector { public officeId: number; static $inject = [ "jobFact"] constructor( private jobFact) { } $onChanges(changesObj) { if (changesObj.officeId) { let msg = "Changed from " + changesObj.officeId.previousValue + " to " + changesObj.officeId.currentValue; console.log(msg) } } } app.component("clientSelector", { template: `` , bindings: { officeId: "<" } , controller: clientSelector , controllerAs: "vm" }); }
So, what is happening here is the onChanges function is actually tracking all the bindings. When the value changes, the changesObj will have a .previousValue and a .currentValue. At that point, you can do whatever you want; change something in the component, like we were doing with dropdown when officeId changed, or even throw something back to the parent with a bound function.
All you need to know is that $watch is dead.
[disqus]