Angular 2 Directives

Angular 2 app is a set of HTML templates. Angular 2 transforms the DOM by taking in consideration the directives instructions. Then angular 2 render the final View.

angular 2 directives
angular 2 directives

live example at the end of the article

Try it yourself,Live Example

try angular 2 directives
try angular 2 directives

A directive is simply a class with a specific Metadata (@Directive decorator)

what’s a directive
what’s a directive

 

We have three kinds of directives:

 

  1. Components: yes a component is a directive. (@Component)
  • A component is a directive with a template.
  • @Component decorator extends the @Directive
  • In angular 2 applications the component is the main
  1. Structural directives: alters the DOM, it adds, removes or replaces elements.

(e.g. NgIf : helps to show or hide an element )

Click the try example to see Structural directive in action:

try angular 2 directives
try angular 2 directives

 

  1. Attribute directives: alters the Element by changing its behavior or the appearance

(e.g. NgClass : it adds a class to an element. e.g. span)

Try it yourself,Live Example

try angular 2 attribute directive
try angular 2 attribute directive

We create our Structural directives.

 Structural directive
Structural directive

 

keep in mind that when you create a directive is similar to create a component.

  1. Import the @Directive decorator. (import {Directive} from ‘angular2/core’;)
  2. To identify the directive we need a CSS selector. (@Directive({ selector: ‘[myUnless]’ }))
  3. Do not use ng as prefix for your directive. (in our example we use my)
  4. We add a public input to our Directive. (@Input() set myAngular2Directive(condition: boolean))
  5. The directive shows the element if the expression evaluated into false.
/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {Directive, Input} from 'angular2/core';
import {CORE_DIRECTIVES} from 'angular2/common';
import {TemplateRef, ViewContainerRef} from 'angular2/core';

/*Angular 2 myAngular2MyDirective*/

@Directive({ selector: '[myAngular2Directive]' })
export class Angular2Directive {

    constructor(
        private _templateRef: TemplateRef,
        private _viewContainer: ViewContainerRef
    ) { }

    @Input() set myAngular2Directive(condition: boolean) {
        if (condition) {
            this._viewContainer.clear();
        }
        else {
            this._viewContainer.createEmbeddedView(this._templateRef);

        }
    }
}
Attribute directives
Attribute directives

 

Angular 2 Attribute Directive

structural directive

attribute directive