Angular Custom Directives

Angular Custom Directives

Custom directives are an easy way to specify functionality to a DOM object while keeping the complexity hidden from the UI devs.

My thanks to https://malcoded.com/posts/angular-custom-directives/

USE CASES:
Let's say you need to programatically set the background color of a button (CASE 1).

...or, let's say you want to listen for a specific action to happen on your page (CASE 2).

USAGE: Copy and paste the code samples below into the Javascript console in your browser, then simply hit return on your keyboard to see the code in action.

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

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

export class ExampleDirective {

  constructor(elementRef: ElementRef) { 
    elementRef.nativeElement.style.backgroundColor = 'red'; //set the bgcolor to red
  }

}


//CASE 2
//make the custom directive react to user events
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core'

@Directive({
  selector: '[appExample]',
})
export class ExampleDirective {
  constructor(private elementRef: ElementRef, private renderer: Renderer2) {
    this.setBgColor('white')
  }

  setBgColor(color: string) { //handy code that shows the DOM path to change an object's CSS value
    this.renderer.setStyle(
      this.elementRef.nativeElement,
      'backgroundColor',
      color
    )
  }

  @HostListener('mouseenter') onMouseEnter() {  //use this decorator to listen for an event, then fire an action
    this.setBgColor('yellow')
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.setBgColor('teal')
  }
}



<div style="text-align:center">

  
<h3>Button example to demonstrate the custom directive</h3>
<button appExample defaultColor="green">Button</button>
<!-- the custom directive name is "appExample", so just include it in the tag of the DOM 
element you want to apply it to (like the button above) -->
</div>

<router-outlet></router-outlet>


Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/angular/angular-custom-directives/