angularjsangularjs-components

What is a component in AngularJS?


I was doing some reading about directives and was wondering what the distinction was between a directive and a component, when I found that there are lots of components in AngularJS.

There is a function component, type component, service component, filter component, provider component, etc... Then to top it off I found that a module component is a component consisting of directives, services, filters, providers, templates, global API’s, and testing mocks. That tended to make things more confusing. I couldn't find a definition of a "component" in the Angular documentation that would explain the distinctions between the types of components listed.

So what exactly is a "component" in AngularJS? Is it something as simple as reusable blocks of code?

By the way, I'm using Angular version 1.4.2 currently.


Solution

  • Angular components were introduced in version 1.5.

    A component is a simplified version of a directive. It cannot do dom manipulation (not link or compile methods) and "replace" is gone too.

    Components are "restrict: E" and they are configured using an object (not a function).

    An example:

      app.component('onOffToggle', {
        bindings: {
          value: '=',
          disabled: '='
        },
        transclude: true,
        template: '<form class="form-inline">\
                           <span ng-transclude></span>\
                           <switch class="small" ng-model="vm.value" ng-disabled="vm.disabled"/>\
                         </form>',
        controllerAs: 'vm',
        controller: ['$scope', function($scope) {
          var vm = this;
          $scope.$watch("vm.disabled", function (val) {
            if (!val) {
              vm.value = undefined;
            }
          })
        }]
      });
    

    Further reading: https://toddmotto.com/exploring-the-angular-1-5-component-method/