如何使用Angular组件观察组件绑定更改

Dor*_*hen 35 javascript angularjs typescript angularjs-components

如何监听角度组件绑定更改并执行操作?

angular.module('myapp')
    .component('myComponent', {
        templateUrl: 'some.html',
        controller: MyController,
        controllerAs: 'myCtrl',
        bindings: {
            items: '<'
        }
    });
Run Code Online (Sandbox Code Playgroud)

现在当items我想要使​​用此值执行其他操作时,我该
怎么办?

小智 59

您可以将$onChanges方法添加到控制器

$onChanges(changesObj)在更新单向绑定时调用.changesObj是一个哈希,其键是已更改的绑定属性的名称,值是表单的对象.

以下示例处理canChange更改事件.

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'
});
Run Code Online (Sandbox Code Playgroud)

需要AngularJS> = 1.5.3并且仅适用于单向数据绑定(如上例所示).

文档:https://docs.angularjs.org/guide/component

参考:http://blog.thoughtram.io/angularjs/2016/03/29/exploring-angular-1.5-lifecycle-hooks.html

  • 如果它可以帮助其他任何人:请注意,这仅适用于较新的单向绑定语法("<"),而不适用于使用"="的更"传统"的双向绑定.它记录在案,但很容易错过,因为我学到了很多困难.:-P (6认同)

bas*_*rat 27

现在当项目更改时我想使用此值执行另一个操作,我该怎么办?

但我想避免使用垂死的$ scope

如果你希望使用$scope,你可以使用属性setter方法来检测任何改变,例如:

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
Run Code Online (Sandbox Code Playgroud)

请注意,你不应该将其用于复杂的逻辑(原因:https://basarat.gitbooks.io/typescript/content/docs/tips/propertySetters.html)


jfr*_*rej 7

这是basarat 答案的ES5.1版本:

function MyController() {
  var items = [];

  Object.defineProperty(this, 'items', {
    get: function() {
      return items;
    },

    set: function(newVal) {
      items = newVal;
      console.log('Items changed:', newVal);
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

使用Object.defineProperty().受所有主流浏览器和IE9 +支持.