Tuesday, March 15, 2016

Angular 1.5 - Stateless components

Angular 1.5 brings us ‘Components’, a special kind of directive that uses a simpler configuration. It is a first step towards Angular 2.0 where directives and controllers no longer exist and are replaced by a component-based model.

Advantages and disadvantages of components

From the Angular documentation:

Advantages of Components:

  • simpler configuration than plain directives
  • promote sane defaults and best practices
  • optimized for component-based architecture
  • writing component directives will make it easier to upgrade to Angular 2

When not to use Components:

  • for directives that rely on DOM manipulation, adding event listeners etc, because the compile and link functions are unavailable
  • when you need advanced directive definition options like priority, terminal, multi-element
  • when you want a directive that is triggered by an attribute or CSS class, rather than an element

Most important to remember is that components have their own isolated state(meaning that only isolated scope is supported) and that no DOM interactions are possible.

An example

I created a small ‘PreviousNext directive’ that enable/disable previous/next buttons in a wizard. This directive uses state on a higher level wizardcontroller.

Here is the original code:

I decided to rewrite this directive to a component but to keep things simple I left most of the state in the wizardcontroller.

Here is the code rewritten as a component:

Let’s have a look at the main differences:

  • We didn’t specify a controller meaning that Angular creates one for us behind the scenes. It also creates a controllerAs value for us, $ctrl by default. So the $ctrl calls inside the template are calling a generated controller available through the $ctrl alias.
  • We used bindings to control the inputs and outputs of our component. Inputs are bound with the ‘<’  symbol and indicates a one-way binding. Output are bound with the ‘&’ symbol and function as callbacks to events. So we read out the currentStep value, call onNext, onPrevious and isLastStep functions on our generated controller that are routed to functions on the parent  (wizard)controller.

I could further improve this component by moving all the previous/next logic inside the component and call a function to feed the currentStep back to the wizardController. But this is an exercise I leave up to the reader… Smile

No comments: