Angular 2.0 – Directives

Directives are the classes with @Directive decorator. They give special instructions to Angular. Angular use these instructions when it renders the templates and transform to DOM. It is also clear that Angular templates are dynamic.

A Component (@Component) is technically a directive – A directive with a template. So @Component is a @Directive extended with template features. Yet different form other Directives.

There are two types of Directives :

  • Structural
  • Attribute

Structural Directives

They alters the layout of elements either by replacing, adding, or removing them from DOM. *ngFor and *ngIf are the two most common Structural Directives in Angular. They are same as foreach loop and If condition respectively in programming languages.
Examples:
<li *ngFor =”let user of Users”></li>
This is like foreach where you say that foreach(var user in Users), So it is iterating through the list of Users and displaying them one by one in an unordered list

<div *ngIf=”users”>
//Do something
</div>

It is like If condition. In the above example if there are users then only the stuff inside that div tag is rendered.



Attribute Directives

These directives alters the appearance or behavior of existing elements. They appear like regular HTML attributes. An example of this kind is ng-model
Example:
<input [(ng-model)] = “user.name”>
Here it modifies the behavior of existing element i.e., <input> by setting its display value property and responding to change events.

Other examples arengStyle and ngClass