How can I listen to angular component binding change and perform actions?
angular.module('myapp') .component('myComponent', { templateUrl: 'some.html', controller: MyController, controllerAs: 'myCtrl', bindings: { items: '<' } });
now when items
changes I want to perform another action using this value,
How can I do it?
You can add the $onChanges
method to the controller
$onChanges(changesObj)
is called whenever one-way bindings are updated. The changesObj is a hash whose keys are the names of the bound properties that have changed, and the values are an object of the form.
Following example handles canChange
change event.
angular.module('app.components', []) .component('changeHandler', { controller: function ChangeHandlerController() { this.$onChanges = function (changes) { if (changes.canChange) this.performActionWithValueOf(changes.canChange); }; }, bindings: { canChange: '<' }, templateUrl: 'change-handler.html' });
Requires AngularJS >= 1.5.3 and works only with one-way data-binding (as in the example above).
Docs: https://docs.angularjs.org/guide/component
Reference: http://blog.thoughtram.io/angularjs/2016/03/29/exploring-angular-1.5-lifecycle-hooks.html
now when items changes I want to perform another action using this value, How can I do it?
But I want to avoid using the dying $scope
If you don't want to use $scope
you can use a property setter to detect any changes e.g. :
class MyController { private _items: string[] = [] set items(value:string[]){ this._items = value; console.log('Items changed:',value); } get items():string[]{ return this._items; } } const ctrl = new MyController(); ctrl.items = ['hello','world']; // will also log to the console
Please note that you shouldn't use it for complex logic (reasons : https://basarat.gitbooks.io/typescript/content/docs/tips/propertySetters.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