How to watch component binding change using Angula

2019-01-23 10:46发布

问题:

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?

回答1:

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)