如何使用 Angular 组件查看组件绑定变化

How to watch component binding change using Angular component

如何监听 angular 组件绑定变化并执行操作?

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

现在,当 items 发生变化时,我想使用该值执行另一个操作,
我该怎么做?

我发现了一种方法,但不确定它是否最有效。首先引入 $scope 作为依赖项,并在构造函数中将其设置为 this._scope 等。我的 $onInit 函数中有以下内容:

this._scope.$watch(() => {
    return this.items;
  },
  (newVal, oldVal) => {
    // Do what you have to here
  });

这里的答案给了很大启发:Angularjs: 'controller as syntax' and $watch

希望对您有所帮助,除非有人告诉我,否则我将一直使用它。

目前您不能在没有 $scope 的情况下使用 angular 观察器,因为更改检测是基于 $scope 的。即使您在 HTML 中使用表达式,它也会 delegate watch functionality to $scope.

即使您创建了一些其他的监视机制,您也需要记住手动取消监视 - 而使用 $scope 它会自动完成。

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

如果你不想使用$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

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

这是 的 ES5.1 版本:

function MyController() {
  var items = [];

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

    set: function(newVal) {
      items = newVal;
      console.log('Items changed:', newVal);
    }
  });
}

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

您可以将$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'
});

需要 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

这种方法可能会有所帮助:

import { Input } from '@angular/core';

class MyComponent {
  @Input set items(value) {
    if (this._items !== value) {
      console.log(`The value has been changed from "${this._items}" to "${value}"`);
      this._items = value;
    }
  }

  private _items;  
  
  get items() {
    return this._items;
  }
}