AngularJS Component: How to avoid watchers for unused bindings

All we need is an easy explanation of the problem, so here it is.

I have a component repeating quite a few times and would like to avoid excessive watching.

  angular
    .module('myModule')
    .component('component', {
      template: '',
      bindings: {
        code: '@',
        problemBinding: '<',
      },
      controller: componentController,
    });

Each < binding seems to create a watcher despite the fact that most of the components are not using problem-binding argument in the html. This is demonstrated in this plunkr where each new < binding creates as many watchers as the component is being repeated.

Is there a way to use problemBinding so that it creates a watcher for the component if and only if the argument is being used?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

  angular
    .module('myModule')
    .component('component', {
      template: '',
      bindings: {
        code: '@',
        problemBinding: '<?',
      },
      controller: componentController,
    });

All 4 kinds of bindings (@, =, <, and &) can be made optional by adding ? to the expression. The marker must come after the mode and before the attribute name.

For more information, see

Method 2

If your most of the components are not using ‘problemBinding’, make it optional otherwise it will create watch for that binding in spite of being used. Can refer angular docs.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply