14

has anyone created any sample Angular Directive using @Directive decorator? I searched a lot on however all developers so far created component directives. Even Angular API Review doesn't speak more on this.

rjdkolb
  • 10,377
  • 11
  • 69
  • 89
Avi Kenjale
  • 2,414
  • 6
  • 29
  • 46
  • 5
    [Developer guides -> 12. Attribute directives](https://angular.io/docs/ts/latest/guide/attribute-directives.html)... – Eric Martinez Jan 27 '16 at 22:02
  • Also, [Dev guide - 13. Structural Directives](https://angular.io/docs/ts/latest/guide/structural-directives.html), the _unless_ directive. – Mark Rajcok Jan 28 '16 at 00:15
  • well explained answer here please have a look at this http://stackoverflow.com/a/34616190/5043867 – Pardeep Jain Feb 19 '16 at 05:08

5 Answers5

18

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;
     }

 }
micronyks
  • 54,797
  • 15
  • 112
  • 146
10

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]'
})
Pratik Kelwalkar
  • 1,592
  • 2
  • 15
  • 21
5

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

guyoung
  • 129
  • 1
3

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

ritz078
  • 2,193
  • 3
  • 22
  • 24
0

As per Angular2 docs, directives are used to change the behaviour of the DOM element.

Lets create one directive which would change the backgroundcolor of the div to red in case of mouseenter and yellow in case of mouseleave.

Step 1: Create Component

import {Component} from '@angular/core';

@Component({
  selector: 'my-comp',
  template: '<div colorFlip>This is just a Demo!</div>'
})

export class MyComp {}

Step 2: Create Directive

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

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

export class ColorFlip {
  constructor(private el: ElementRef) {}
  @HostListener('mouseenter') handleMouseEnter() {
    this.flipColor('red');
  }

  @HostListener('mouseleave') handleMouseEnter() {
    this.flipColor('yellow');
  } 

  flipColor(color:string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
} 

Step 3: Register Directive

@NgModule({
  imports: [...],
  declarations: [MyComp , ColorFlip ]
})
Suneet Bansal
  • 2,664
  • 1
  • 14
  • 18