What are Directives and What Types Exist in Angular?

What are Directives in Angular?

Directives are special classes in Angular that extend HTML element behavior. They allow changing DOM structure, adding styles or dynamically managing component logic.

Directive Types in Angular

Angular divides directives into three main categories:

TypePurposeExamples
AttributeChange element appearance or behaviorngClass, ngStyle, customHighlight
StructuralChange DOM structure (add/remove elements)ngIf, ngFor, ngSwitch
CustomDirectives you create for adding reusable logicappTooltip, appValidate

Attribute Directives

Applied to element as attributes. They can change:

  • element style (ngStyle)
  • class (ngClass)
  • behavior through event listeners

Example: ngClass

<div [ngClass]="{ active: isActive }">Text</div>

Custom Attribute Directive Example

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(el: ElementRef) {
    el.nativeElement.style.backgroundColor = 'yellow';
  }
}
<p appHighlight>Highlighted text</p>

Structural Directives

Change DOM structure: add/remove elements.

Examples

<div *ngIf="isVisible">Show</div>
<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>
  • *ngIf — conditional rendering.
  • *ngFor — array iteration.
  • *ngSwitch — multiple branching.

Creating Custom Directive

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

@Directive({
  selector: '[appZoom]'
})
export class ZoomDirective {
  constructor(private el: ElementRef) {}

  @HostListener('mouseenter') onEnter() {
    this.el.nativeElement.style.transform = 'scale(1.1)';
  }

  @HostListener('mouseleave') onLeave() {
    this.el.nativeElement.style.transform = 'scale(1)';
  }
}
<img src="..." appZoom />

Difference from Components

CharacteristicDirectiveComponent
Selector[appDirective] (attribute)<app-component> (tag)
TemplateNoYes
UsageAs behavior or styleAs UI element

Tip:

Use directives for reusable behavior that doesn't require template. If UI is needed — better create component.