Srikanth Technologies

Creating Custom Directives in Angular

In this blog, I create custom directives in Angular and show how to use them in Angular component.

In order to create a custom attribute directive, we need to take the following steps:

Custom Directive - TodayDirective

The following directive is an attribute directive used to place system date in the element that uses this attribute.

Here are the files related to it.

today.directive.ts

import { Directive, ElementRef, Renderer } from '@angular/core';
 
@Directive({
    selector: '[stToday]',   // attribute to be used 
})
export class TodayDirective {
     constructor( element: ElementRef , renderer : Renderer) {
        var today = new Date().toDateString()
        renderer.setElementProperty(element.nativeElement,'innerText', today)  // channge innerText property of the element 
        
     }
 }

use-custom-directive.component.ts

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

@Component({
    selector: 'st-use-custom-directive',
    templateUrl : 'user-custom-directive.component.html'
})
export class UseCustomDirectiveComponent  {
     
}

use-custom-directive.component.html

<h1  stToday></h1>

When you run UseCustomDirectiveComponent, the content of h1 is replaced with system date. See the screenshot at the end of the blog.

App.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { TodayDirective } from './today.directive';
import { UseCustomDirectiveComponent } from './use-custom-directive.component';
 
@NgModule({
  declarations: [
     UseCustomDirectiveComponent, TodayDirective
  ],
  imports: [
    BrowserModule  
  ],
  providers: [],
  bootstrap: [UseCustomDirectiveComponent]
})
export class AppModule { }

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Custom Directives</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <st-use-custom-directive></st-use-custom-directive>
</body>
</html>

HighlightDirective

This directive is to highlight the element by changing color and size of the element that is associated with it whenever mouse moves onto it. It changes size and color of the element as mouse moves onto it and then preserves the original color and size of the element when mouse moves out of the element.

Here are the files related to it.

Highlight-directive.ts

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

@Directive({
    selector: '[stHighlight]',
})
export class HighlightDirective {
     orgSize : string;
     orgColor : string;
     
     // Receive input - color and size - from client 
     @Input('size')  size : string = '20pt';  
     @Input('color') color : string = 'red'; 
      

     constructor( private element: ElementRef , private renderer : Renderer) {
          // preserve original color and font-size 
          this.orgSize = element.nativeElement.getAttribute("font-size")
          this.orgColor = element.nativeElement.getAttribute("color")
     }
     
     // Listen to event of the client - mouseenter
     @HostListener('mouseenter') onMouseEnter() {
        // set new color and font-size
        this.renderer.setElementStyle(this.element.nativeElement, 'font-size',this.size);
        this.renderer.setElementStyle(this.element.nativeElement, 'color',this.color);
     }

    // Listen to event of the client - mouseleave
    @HostListener('mouseleave') onMouseLeave() {
        // restore original color and font-size
        this.renderer.setElementStyle(this.element.nativeElement, 'font-size',this.orgSize);
        this.renderer.setElementStyle(this.element.nativeElement, 'color',this.orgColor);
    }
}

A few points about the code:

We have to include this directive in app.module.ts as follows:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { TodayDirective } from './today.directive';
import { HighlightDirective } from './highlight.directive';
import { UseCustomDirectiveComponent } from './use-custom-directive.component';

@NgModule({
  declarations: [
     UseCustomDirectiveComponent, TodayDirective, HighlightDirective
  ],
  imports: [
    BrowserModule  
  ],
  providers: [],
  bootstrap: [UseCustomDirectiveComponent]
})
export class AppModule { }

Modify use-custom-directive.component.html as follows to use new custom directive:

<pre class="code">
<h1  stToday></h1>

<div stHighlight  size="20pt">Srikanth Technologies</div>

<div stHighlight  color="green"  size="30pt">Srikanth Pragada</div>
When the attribute directive stHighlight is used, the component (div) is automatically passed to HighlightDirective and it starts listening to its events. Value passed to color attribute is automatically passed to input property color in HighlightDirective class.

The following image shows directive in action when mouse moves over first div.

Post Your Comment

Image
Enter the code given in the above image :
Enter Your Name :
Enter Your Email Address :
Enter Your Comment :

Comments