In this article, we focus on an important Angular concept called - Directives, its use, and how to build them. 

What Are Directives in Angular?

Angular is the fourth (22.29%) most used web framework for front-end development using HTML and typescript programming language. Built by Google in 2009, Angular is used for single-page applications (SPAs) that are lighter and faster, HTML templates, and components–driven dynamic applications. Popular websites written in Angular are Forbes, Microsoft Office Home, IBM, and Google Marketing Platform.

Directives in Angular are a fundamental development concept. So, let’s take a detailed look at them.

In Angular, Directives are defined as classes that can add new behavior to the elements in the template or modify existing behavior.

The purpose of Directives in Angular is to maneuver the DOM, be it by adding new elements to DOM or removing elements and even changing the appearance of the DOM elements.

What Is Meant By Directives in Angular?

Directives are meant to be a function that executes when found in the DOM by the Angular compiler to extend the power of the HTML with new syntax. Directives have a name and can be predefined or custom-defined so that they can be called anything. Depending on the predefined directive, its use is determined – attribute, comment, element, or class.

Types of Directives in Angular

Directive in angular can be categorized into the following types: Component Directive, Structural Directive, and Attribute directive.

Let’s consider each of these Angular Directive types separately.

Component Directive

Special directives in Angular are called Components since this type of directive has a template or template URLs. In effect, it is a component directive that shows something in DOM.

Structural Directive

This type of directive is used to make changes in the layout of the DOM. Elements can be added or removed, hence changing the structure of the DOM. An example would be *ngIf(adding or removing element from DOM) or *ngFor(lists elements of every iteration).

Attribute directive

This type of angular directive is used to make behavior or element changes in the appearance and behavior of an element. For example, ngStyle( applying styles) or ngClass(applying CSS classes).

Let’s explore the attribute directive some more by making our own Attribute Directive.

Creating Our Own Attribute Directive

The purpose of the following attribute directive is to change the text color whenever the pointer hovers over it.

Custom Directive is very similar to creating the Angular component. The custom directive is created using the @Directive decorator to replace the @component decorator.

  1. Create a class with @Directive
  2. Create an Attribute directive with Element Ref
  3. Listen to the Hover event with
  4. HostListener

By using handlers, the element is referenced, and the color of the text is changed.

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

@Directive({

selector:'[highlight]',

})

export class HighlightDirective{

constructor (private eleRef: ElementRef){ }

@HostListerner ('mouseover') on MouseOver(){

this.eleRef.nativeElement .style.color ='green';

}

@hostListener('mouseleave') onMouseLeave(){

this.eleRef.nativeElement.style.color='black' ;

}

}] 

Passing Input to Directives

Another way is to input the color name for the directive.

Input Method 1:

1. @Input( ) within the directive class with the same name as the directive name:  (@Input ( ) highlight ;)

2. value is passed as follows: 

<p highlight =”blue”> Highlight Directive </p>

Input Method 2:

1. @Input ( ) using any variable name:

(@Input( ) colorName;)

2. value is passed as follows:

<p highlight =”red” colorName =”black”> Highlight Directive</p>

In the following section, let’s work on making a structural directive in Angular.

Creating Our Own Structural Directive

This directive focuses on changing the content, either adding it or removing it based on a value, just like ngIf

1. Create class with @Directive and object is passed with selector, name of the directive.

2. Create a Structural directive with ViewContainerRef and TemplateRef

  • ViewContainerRef – will hold reference to the host element and host the directive or component.
  • TemplateRef- will hold references to templates identified by ng-template.

These two dependencies are then injected into the constructor of the directive class.

3. Next @input( )  is created with a variable name, which is similar to the directive name to indicate adding or removing the content.

4. Here, we have to ensure changes to the content based on the value

  • Create ngOnChanges() lifecycle hook method

5. In the final step,  the value of ngOnChanges is checked

  • The content is removed when the value is – false: containerRef is cleared
  • The content is shown when the value is – true: templateRef is added into ContainerRef

Hence, the structural directive in Angular is completed.

Build Composable Web Applications

The future of applications is building ‘composable’ applications, where functional parts are readily dissociated from an application so that better applications can be made with higher levels of functionality.

How to Create Custom Directives?

In this section, we explore building custom directives in angular. Since the approach differs from one developer to the next, there is no standardization of directives in this category.

Steps to Build Custom Directives:

At the command line, the following command is added:

Ng g directive directiveName

Example: ng g directive changeText

At the command line, the following sequence plays out: 

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

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

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

import { NewCmpComponent } from './new-cmp/new-cmp.component';

import { ChangeTextDirective } from './change-text.directive';

@NgModule({

   declarations: [

   AppComponent,

   NewCmpComponent,

   ChangeTextDirective

   ],

   imports: [

   BrowserModule

   ],

   providers: [],

   bootstrap: [AppComponent]

})

export class AppModule { }

The file will now include the declarations and the ChangeTextDirective class. Additionally, it is imported from @angular/core

change-text.directive

In this directive, which is imported from the core, we proceed to change text.

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

@Directive({

selector: '[changeText]'

})

export class ChangeTextDirective {

constructor() { }

}

In the file, the directive in angular includes the selector property. To match the view, we define the selector as per view by assigning a custom directive.

In the following section, we add the directive to the app.commponent.html view in the following manner:

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

<span changeText >Welcome to {{title}}.</span>

</div>

The above changes have to now reflect in change-text.directive.ts in the following manner: 

change-text.directive.ts

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

@Directive({

selector: '[changeText]'

})

export class ChangeTextDirective {

constructor(Element: ElementRef) {

console.log(Element);

Element.nativeElement.innerText="Text is changed by changeText Directive. ";

}

}

In the file, the class is the ChangeTextDirective and the constructor for ElementRef, a type of element.  This element includes all the details, and the Change Text directive is applied here.

In the final step, another element is added to console.log. The output can be viewed from the browser console. Changes can be made to the text as well as seen above.

Thus, in Angular, you can compose decoupling software sections that are easily workable on frameworks like Node or React.  As a developer, you should enhance your capabilities by using collaborative component-building service providers. 

Conclusion

If you are looking to enhance your software development skills further, we would highly recommend you check Simplilearn’s Full Stack Java Developer. This program is designed in collaboration with Caltech CTME and can help you hone the relevant skills. The live industry projects during the course of the program will help you become job-ready in no time. 

If you have any questions or doubts, feel free to post them in the comments section below. Our team will get back to you at the earliest.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 24 Feb, 2025

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 8 Jan, 2025

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 8 Jan, 2025

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449

Get Free Certifications with free video courses

  • Getting Started with Full Stack Development

    Software Development

    Getting Started with Full Stack Development

    12 hours4.552K learners
  • Full-Stack Development 101: What is Full-Stack Development ?

    Software Development

    Full-Stack Development 101: What is Full-Stack Development ?

    1 hours4.415K learners
prevNext

Learn from Industry Experts with free Masterclasses

  • Key 2025 Software Development Trends- Learn How To Leverage them for your career

    Software Development

    Key 2025 Software Development Trends- Learn How To Leverage them for your career

    9th Dec, Monday9:30 PM IST
  • Must-Know Full Stack Java Dev Career Trends for 2024

    Software Development

    Must-Know Full Stack Java Dev Career Trends for 2024

    6th Aug, Tuesday9:00 PM IST
  • Full Stack Java Development: A 2024 Blueprint for Recession-Proofing Your Career

    Software Development

    Full Stack Java Development: A 2024 Blueprint for Recession-Proofing Your Career

    27th Jun, Thursday7:30 PM IST
prevNext