How to watch component binding change using Angular component

前端 未结 5 2049
醉梦人生
醉梦人生 2020-12-14 15:04

How can I listen to angular component binding change and perform actions?

angular.module(\'myapp\')
    .component(\'myComponent\', {
        templateUrl: \'         


        
5条回答
  •  温柔的废话
    2020-12-14 15:24

    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

提交回复
热议问题