Angular Directive

There are three kinds of Angular directives:

Components
Attribute directives
Structural directives

Angular2 Guide Attribute Directives Code : https://github.com/guyoung/GyPractice-Angular2/tree/master/apps/attribute-directives

Angular2 Guide Structural Directives Code : https://github.com/guyoung/GyPractice-Angular2/tree/master/apps/structural-directives


Here's a sample directive. This add a event listener for click done outside a component.

import {Directive, ElementRef, HostListener, EventEmitter, Output} from '@angular/core';

@Directive({
  selector: '[clickedOutside]'
})
export class ClickedOutsideDirective {
  @Output()
  public clickedOutside = new EventEmitter();

  constructor(private _elemRef: ElementRef) {
  }

  @HostListener('document:click', ['$event'])
  public onClick(event) {
    const targetElement = event.target;
    if (!targetElement) {
      return;
    }
    /**
     * In case the target element which was present inside the referred element
     * is removed from the DOM before this method is called, then clickedInside
     * will be false even if the clicked element was inside the ref Element. So
     * if you don't want this behaviour then use [hidden] instead of *ngIf
     */
    const clickedInside = this._elemRef.nativeElement.contains(targetElement);
    if (!clickedInside && !this._elemRef.nativeElement.isSameNode(targetElement)) {
      return this.clickedOutside.emit(event);
    }
  }
}

This can be used as follows:

<app-comp (clickedOutside)='close()'></app-comp>

close will be triggered whenever someone clicks outside app-comp


Simple-Directive-Demo . This is a very simple example to start with angular2 directive.

I have a component and directive.

I use directive to update component's view. Moreover directive's changeColor function is getting called with a component's changeColor function.

Component

@Component({
  selector: 'my-app',
  host: {'[style.backgroundColor]':'color',}
  template: `
      <input type="text" [(ngModel)]="color" (blur)="changeColor(color)" />
      <br>
      <span > (span) I'm {{color}} color <span>
      <div mySelectedColor [selectedColor]="color"> (div) I'm {{color}} color </div>
    `,
    directives: [selectedColorDirective]
})

export class AppComponent implements AfterViewInit{
  @ViewChild(selectedColorDirective) myDirective: selectedColorDirective;
  color:string;
  constructor(el:ElementRef,renderer:Renderer) {
    this.color="Yellow";
    //renderer.setElementStyle(el, 'backgroundColor', this.color);
  }
  changeColor(color)
  {
    this.myDirective.changeColor(this.color);
  }
  ngAfterViewInit() { }
 }

Directive

@Directive({

  selector:"[mySelectedColor]", 
    host: {
   // '(keyup)': 'changeColor()',
   // '[style.color]': 'selectedColor',
  }

  })

  export class selectedColorDirective { 

    @Input() selectedColor: string = ''; 

    constructor(el: ElementRef, renderer: Renderer) {
      this.el=el;
        this.el.nativeElement.style.backgroundColor = 'pink'; 
      // renderer.setElementStyle(el, 'backgroundColor', this.selectedColor);
    } 

    changeColor(clr)
    {
     console.log('changeColor called ' + clr);
     //console.log(this.el.nativeElement);
     this.el.nativeElement.style.backgroundColor = clr;
     }

 }

In Simple Terms Component Directive will be your directives with template which we use a lot while building a app -> in your html -> <custom-tag></custom-tag>

@Component({
selector : 'custom-tag',
template : '<p> My Custom Tag</p>'
})

Structural Directive are the ones that modify the DOM, by removing adding elements. Example would be

<div *ngIf="showErrorMessage">{{errorMessage}}</div>

ngIf would add the div if true else remove if it changes to false.

Lastly are the Attribute Directive, the name says it all..its a 'attribute based directive' Example would be :

<input type="text" pPassword />

@Directive({
    selector: '[pPassword]'
})