Custom Directives in Angular

Posted by: admin
Category: Angular

Directives in Angular

Angular directives are the functions that are executed whenever Angular compiler identifies it. As the name suggests Angular directives increase the capability of HTML elements by attaching custom behaviors to the DOM i.e. Giving direction to the HTML elements.

Types of directives

There are three types of directives in Angular.

  1. Attribute Directives

The Directives are used for changing appearance and behavior of DOM elements that is responsible to render HTML elements and attaching a behavior. We can use it to change the style of DOM elements by making runtime changes in the CSS Styles and its classes.

These directives are also used to conditionally hide or show particular DOM elements. There are many built-in Attribute Directives like NgStyleNgClass, etc.

  1. Structural Directives

The Directives are used for changing the structure of the DOM. It is generally used for dynamically adding or removing the elements from the DOM.

You can easily differentiate between the Structural and Attribute Directive from it’s syntax. The Structural Directive’s name always starts with an asterisk (*) prefix and Attribute Directive does not contain any prefix.

There are three most popular Structural Directives.

*NgIf.

*NgFor.

*NgSwitch.

  1. Components Directives

Components are directives with templates. Template is the only difference between Components and the other two types of directives. So, we can say that the Component is a cleaner version of the Directive with a template, These helps us to reuse the code snippet as and when required, making sure that the concept of OOPS are being implemented in the angular framework.

Exploring Custom Directives

Custom Directives are used in Angular to extend the functionality of HTML. These are defined by ‘directive’ function. A custom directive just replaces the element for which it is activated.

Custom Attribute Directive

For creating a custom directive, we need to creating an Angular component and also we have to replace @component decorator with the @directive decorator.

So, here we are going to create our first Custom Attribute directive and In this directive we are highlighting the selected DOM element by displaying an element’s background color.

In this application first of we are creating a directive file call as ‘highlight.directive.ts’ in src/app folder and add below mention code into it.

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

@Directive({

  selector: '[appHighlight]'

})

export class HighlightDirective {

constructor(elementRef: ElementRef) {

elementRef.nativeElement.style.backgroundColor = 'red'

  }

}

So, here we have imported Directive and ElementRef from angular-core framework. Directive providing the functionality of @directive decorator where we provide its property selector as a ‘appHighLight’ So that we can use it across the application. We have also implemented ‘ElementRef’ which is work for accessing the DOM element.

Now we need to add our Directive in the ‘app.module.ts’ file So we can use it across the application.

import { BrowserModule } from '@angular/platform-browser';

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

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { HighlightDirective } from './highlight.directive';

@NgModule({

  declarations: [

    AppComponent,

    HighlightDirective

  ],

imports: [

    BrowserModule,

    AppRoutingModule

  ],

providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

Now we can use our custom directive. I am adding ‘appHighlight’ directive in the ‘app.component.html’ file but you can use it as per your requirement in the application.

<h1 appHighlight>Hello Arpit</h1>

The output are as below.

Custom Structural Directive

As we have created Attribute directive before same as we are creating Structural directive as well.

In this directive we are going to implement the *appNot directive which is work opposite to *ngIf.

So, first of we need to create a directive file call as ‘appNot.directive.ts’ in src/app folder and add below mention code into it.

import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';

@Directive({

  selector: '[appNot]'

})

export class AppNotDirective {

  constructor(

    private templateRef: TemplateRef<any>,

    private viewContainer: ViewContainerRef) { }

    @Input() set appNot(condition: boolean) {

        if (!condition) {

            this.viewContainer.createEmbeddedView(this.templateRef);

        } else {

            this.viewContainer.clear();}

    }

}

Here we have implemented Directive, Input, TemplateRef and ViewContainerRef from @angular/core.

The Input decorator is a communication bridge between the two components. It is sending data from one component to other component using property binding.

TemplateRef used for the embedded template and it is used to define embedded views and these views are linked with the template.

Now we need to add our Directive in the ‘app.module.ts’ file as we added for Attribute directive.

import { BrowserModule } from '@angular/platform-browser';

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

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { HighlightDirective } from './highlight.directive';

import { AppNotDirective } from './app-not.directive';

 

@NgModule({

  declarations: [

    AppComponent,

    HighlightDirective,

    AppNotDirective

  ],

  imports: [

    BrowserModule,

    AppRoutingModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

Now we can use our custom directive. I am adding ‘appHighlight’ directive in the ‘app.component.html’ file but you can use it as per your requirement in the application.

<h1 *appNot=”true”>True</h1><h1 *appNot=”false”>False</h1>

The output are as below.

Structural Directive Output
Structural Directive Output

 

 

 

 

Custom Directives allows the developer to way to enhance the various components and elements of the HTML clan as per requirements. It also allows the developer to reuse the same functionality across the application if required with minimal efforts while constructing them as well as while maintain them in the long run.

Author : Arpit Prakashbhai Patel

Let’s build your dream together.