Angular 2 Directives

The three types of directives in Angular 2 are capable of specific DOM operations.

Eric Simons Up to date (Mar '17) Angular 2

Although directives in Angular 2 share many things in common with directives in Angular 1, they have become well defined in the Angular 2 and each type are capable of specific tasks.

The three types of directives in Angular 2 are attribute directives, structural directives, and components.

You read that right — Angular 2 components are actually just directives under the hood. So what makes them different from the other two types of directives?

Components are directives that have a template.

Before the Component API shipped in Angular 1.5, directives with templates that were used as elements were defined in a similar way as an attribute directive using the same API, which could lead to messy directive declarations that can be hard to grok. Components use the directive API under the hood, but give us a cleaner interface for defining them by hiding a lot of the defaults that would otherwise be cumbersome.

The other two directive types, attribute and structural, do not have templates. Instead, their purpose is specifically tailed to two types of DOM manipulation:

Structural directives change the DOM layout by adding and removing DOM elements.

Attribute directives change the appearance or behavior of an element.

New Built-in Directives

While Angular 1.x shipped with a bunch of (60+) directives, Angular 2's list of directives is much shorter since the new binding syntax eliminates the need for a lot of them by binding directly to a component's attributes or DOM events. For example, in 1.x you'd have something like ng-click="handleClick($event)" for handling click events on an element. The Angular 2 equivalent would look like (click)="handleClick($event)", no more need for an ng-click directive.

We've already covered Components in Angular 2, so in the next chapters we'll be deep diving into structural directives, attribute directives, and a handful of the directives that are built in to Angular 2.