Angular Directives

Introduction

A directive is an authoritative instruction. In simple terms, a directive is a name given to a behavior which can be used widely by calling the name. For example, a component is a directive whose behaviour is to display the template.

Angular directives..

  • Can enhance the functionality of the application
  • Create reusable components
  • Build a more dynamic and interactive user interface

Types of directives

The different categories of angular directives are as follows:


Attribute directives

Attribute directives can be used to modify the appearance or behavior of an element, component or another directive. Attribute directives can listen to events, manipulate the element's properties or add/remove classes or styles dynamically.


Component directives

Components are the most common and powerful type of directive in Angular. They combine HTML templates, styles, and behavior into a reusable entity. Components have their own logic, properties, and lifecycle hooks, allowing you to create complex UI elements or application sections. You can use components by placing them as custom HTML tags in your templates.


Structural directives

Structural directives can be used to add, remove or manipulate the DOM layout around DOM elements. Structural directives modify the structure of the DOM by adding or removing elements based on certain conditions. They are also used as attributes on HTML elements but with a leading asterisk (*) to indicate their special syntax

Create your own custom directive

To create custom directives in Angular, you can use the @Directive decorator to define the directive's metadata and provide a class that implements the desired behavior. You can specify where and how the directive can be used by setting the selector, inputs, outputs and other properties.

A directive can be created using the following CLI command:

ng generate directive directive_name 


Lets create a directive labelled "color" and see what happens

ng generate directive color

Executing the command will generate a directive file and the corresponding test file

color.directive.ts
color.directive.spec.ts

It also imports the directive into parent module or component and declares it.

src/app/color.directive.ts

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

@Directive({
  selector: '[appColor]'
})

export class ColorDirective { }
@Directive()
  • The @Directive() decorator marks a class as an angular directive. Options can be provided under the decorator
  • The options provide configuration metadata that determine the process, instantiation and runtime of the directive
  • selector?When a CSS selector is found in a template, the corresponding directive is identified, triggered and instantiated
    navigation