Custom Directive in Angular

Directives are helpful in changing the appearance, structure, or layout of the DOM. Basically, there are three types of directives available in angular.

  • Component Directives – Directive with a template
  • Structural Directives – Directive that changes structure or layout of DOM
  • Attribute Directive – Directive that changes appearance or behavior of DOM

For creating a custom directive, we can use the Angular CLI command i.e. ng g d directive-name or we can follow the manual procedure. For the manual procedure, steps are:

  • Create a directive class and decorate it with @Directive decorator and mention a selector for the directive inside @Directive decorator.
  • Register the directive in app.module.ts file.
import {Directive} from '@angular/core';

@Directive({
  selector:'[appBackground]'
})
export class BackgroundDirective {
  constructor(){}
} 

To use this directive in any element we need to place the selector on the element.

<h1 appBackground> This is a Heading </h1>

Using ElementRef

The element upon which the directive is attached can be accessible inside the directive by using ElementRef. To use ElementRef we need to inject it into the directive’s constructor.

By using a property called nativeElement of ElementRef, we can access the actual DOM element.

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

@Directive({
  selector:'[appBackground]'
})
export class BackgroundDirective {
  constructor(private el: ElementRef){
    this.el.nativeElement.style.backgroundColor = 'lightgrey';
  }
}

Here we are accessing the actual DOM element by nativeElement and we are adding a CSS style to it.

However performing some operation directly on the actual DOM element using ElementRef like this is not recommended, it will work this way though. We can make use of Renderer to set any styles or classes to the actual DOM element.

We will make use of Renderer2 which is an upgraded version of Renderer. Renderer2 offers some utility methods to manipulate the DOM elements.

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

@Directive({
  selector:'[appBackground]'
})
export class BackgroundDirective {
  constructor(private el: ElementRef, private re: Renderer2){
    this.el.nativeElement.style.backgroundColor = 'lightgrey';
    this.re.setStyle(this.el.nativeElement, 'color','blue');
  }
}

You can try out all the other available methods of Render2 to play with the DOM element.

Related

HostBinding and HostListener in the custom directive.

Leave a Reply

Your email address will not be published. Required fields are marked *