Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to watch component binding change using Angular component

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?

like image 263
Dor Cohen Avatar asked Feb 28 '16 10:02

Dor Cohen


2 Answers

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

like image 164
David Remie Avatar answered Sep 21 '22 17:09

David Remie


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) 🌹

like image 45
basarat Avatar answered Sep 17 '22 17:09

basarat