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

What are directives in Angular?

Angular is fourth (22.29%) most used a web framework for front-end development using HTML and Typescript programming language. Created by Google in 2009, Angular is used for single-page applications (SPAs) that are lighter and faster, HTML templates, and dynamic component-driven 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 look at them in detail.

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

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

Postgraduate Program: Full Stack Web Development

in collaboration with Caltech CTMESign up now

What is meant by directives in Angular?

Directives are intended to be a function that is executed when found in the DOM by the Angular compiler to extend the power of HTML with new syntax. Directives have a name and can be predefined or optionally defined so that they can be called arbitrarily. 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 following types: Component Directive, Structure Directive and Attribute Directive.

Let’s look at each of these types of angle directives separately.

Components Directive

Special directives in Angular are called Components because this type of directive has a template or template URLs. It’s actually a component directive that displays something in the DOM.

Structural directive

This type of directive is used to make changes to the DOM layout. Elements can be added or removed, thus changing the structure of the DOM. An example would be *ngIf(add or remove an element from the DOM) or *ngFor(lists elements from each iteration).

Attribute Directive

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

Let’s explore the attribute directive a bit more by creating our own attribute directive.

Creating our own attribute directive

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

A custom directive is very similar to creating an 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 a Ref element
  3. Listen to the Hover event with
  4. HostListener

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

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

@Directive({

selector:'[highlight]’,

})

export class HighlightDirective{

constructor (private eleRef: ElementRef){ }

@HostListerner(‘mouseover’) at MouseOver(){

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

}

@hostListener(‘mouseleave’) onMouseLeave(){

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

}

}]

Complete course for web developers

To become a MEAN Stack expertCourse overview

Complete course for web developers

Passing input to directives

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

Input Method 1:

1. @Input( ) in the directive class with the same name as the directive name: (@Input ( ) highlight 😉

2. the value is passed as follows:

Lighting Directive

Input method 2:

1. @Input ( ) using an arbitrary variable name:

(@Input( ) colorName;)

2. the value is passed as follows:

Lighting Directive

In the next section, let’s work on creating a structure directive in Angular.

Creating our own structure directive

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

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

2. Create a structure directive with ViewContainerRef and TemplateRef

  • ViewContainerRef – will contain a reference to the host element and host the directive or component.
  • TemplateRef- will contain 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 that is similar to the directive name to indicate adding or removing content.

4. Here we need to provide value based content changes

  • Create an ngOnChanges() lifecycle hook method

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

  • The content is removed when the value is – false: the containerRef is cleared
  • Content is displayed when value is – true: templateRef is appended to ContainerRef

Therefore, the structure directive in Angular is complete.

Build composable web applications

The future of apps is building “composite” apps, where functional parts are easily separated from the app so that better apps with higher levels of functionality can be made.

Free Angular Basic Course

Become a programming pro with the free courseSign up now

Free Angular Basic Course

How to create custom directives?

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

Steps to build custom directives:

Add the following command to the command line:

Ng g directive directiveName

Example: ng g changeText directive

In the command line, the following sequence is executed:

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

   ],

import: [

   BrowserModule

   ],

providers: [],

loading: [AppComponent]

})

export class AppModule {}

The file will now include the declarations and the ChangeTextDirective class. It is also imported from @angular/core

change-text.directive

In this directive, which is imported from the kernel, we continue to change the text.

import { Directive } from ‘@angular/core’;

@Directive({

selector: ‘[changeText]’

})

export class ChangeTextDirective {

constructor() {}

}

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

In the next section, we add the directive to the app.component.html view as follows:

Welcome to {{title}}.

The above changes should now be reflected in change-text.directive.ts as follows:

change-text.directive.ts

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

@Directive({

selector: ‘[changeText]’

})

export class ChangeTextDirective {

constructor (Element: ElementRef) {

console.log(Item);

Element.nativeElement.innerText=”Text changed by changeText directive. “;

}

}

In the file, the class is ChangeTextDirective and the constructor for ElementRef, an element type. This element includes all the details and this is where the text change directive applies.

The final step adds another entry to the console.log. The result can be viewed from the browser console. Changes can be made to the text as seen above.

This way, in Angular you can compose breakaway software sections that are easy to work with in frameworks like Node or React. As a developer, you should improve your capabilities by using service providers to co-build components.

Want to accelerate your career as an experienced Full Stack Web Developer? Leverage Caltech CTME’s academic excellence in a unique bootcamp-style Full Stack Web Development graduate program. Sign up now!

Conclusion

If you’re looking to further improve your software development skills, we highly recommend you check out Simplilearn’s Postgraduate Program in Full Stack Web Development. This program was developed in collaboration with Caltech CTME and can help you hone relevant skills. Live industrial projects during the program will get you up and running in no time.

If you have any questions or doubts, feel free to post them in the comment section below. Our team will contact you as soon as possible.

https://www.simplilearn.com/what-are-directives-in-angular-article

Previous articleSurvey finds IT leaders struggle with application modernization
Next articleRevenue Cycle and Payer News – August 10, 2022