Components in Angular

components

Figure: components

The core concept of any Angular application is the component. In effect, the whole application can be modeled as a tree of these components.

This is how the Angular team defines a component:

A component controls a patch of screen real estate that we could call a view, and declares reusable UI building blocks for an application.

Basically, a component is anything that is visible to the end user and which can be reused many times within an application.

In Angular 1.x we had router views and directives which worked sort of like components. The idea of directive components became quite popular. They were created by using directive with a controller while relying on the controllerAs and bindToController properties. For example:

  1. angular.module('ngcourse')
  2. .directive('ngcHelloComponent', () => ({
  3. restrict: 'E',
  4. scope: { name: '=' },
  5. template: '<span>Hello, {{ ctrl.name }}.</span>',
  6. controller: MyComponentCtrl,
  7. controllerAs: 'ctrl',
  8. bindToController: true
  9. })
  10. );

In fact, this concept became so popular that in Angular 1.5 the .component method was introduced as syntactic sugar.

  1. angular.module('ngcourse')
  2. .component('ngcHelloComponent', {
  3. bindings: { name: '=' },
  4. template: '<span>Hello, {{ $ctrl.name }}.</span>',
  5. controller: MyComponentCtrl
  6. });

原文: https://angular-2-training-book.rangle.io/handout/components/