Sitemap
Wali Muhammad

Wali Muhammad

Consultant Frontend Developer

Press enter or click to view image in full size

Angular Directives — Complete Guide

3 min readMar 4, 2026

--

Angular is a powerful framework for building dynamic web applications. One of its core features is Directives. Directives allow you to manipulate the DOM (Document Object Model), change the behavior of elements, or attach dynamic logic to templates.

  1. What is a Directive?
    A Directive in Angular is a class with a @Directive decorator that lets you extend the behavior of HTML elements, components, or attributes.
    Think of directives as custom instructions you can apply to elements in your HTML.
    Example: You want a button to change color when hovered. You can write a directive to do this.
  2. Types of Directives
    Angular has 3 main types of directives:
    => Component Directives
    => Structural Directives
    => Attribute Directives

Let’s discuss each in detail with examples.\

2.1 Component Directives

  • Components are directives with a template.
  • Purpose: Render HTML in the DOM with dynamic behavior.
  • Used for UI building blocks like headers, cards, forms, and buttons.

Example:

// app.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
template: `
<h1>Welcome to Angular Directives Guide</h1>
<app-card></app-card>
`,
})
export class AppComponent {}
// card.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-card',
template: `<div class="card">This is a card component!</div>`,
styles: [
`.card {
border: 1px solid #ccc;
padding: 15px;
border-radius: 5px;
width: 200px;
text-align: center;
}`
]
})
export class CardComponent {}

When to use: Whenever you need reusable UI elements with a template.

2.2 Structural Directives

  • Definition: Structural directives change the structure of the DOM, i.e., they add or remove elements dynamically.
  • Prefix: Usually start with *.
  • Built-in Angular structural directives:
  1. *ngIf – Conditionally renders an element.
  2. *ngFor – Loops through a list of items.
  3. *ngSwitch – Renders elements based on multiple conditions.

2.2.1 *ngIf and *ngForExample

<div *ngIf="isLoggedIn; else loginTemplate">
Welcome back, user!
</div>
<ng-template #loginTemplate>
<button (click)="login()">Login</button>
</ng-template>
isLoggedIn = false;

login() {
this.isLoggedIn = true;
}

<ul>
<li *ngFor="let user of users">{{ user }}</li>
</ul>
users = ['Ali', 'Sara', 'Dua', 'Ahmed'];

2.2.3 *ngSwitch Example

Get Wali Muhammad’s stories in your inbox

Join Medium for free to get updates from this writer.

<div [ngSwitch]="role">
<p *ngSwitchCase="'admin'">Admin Panel</p>
<p *ngSwitchCase="'user'">User Dashboard</p>
<p *ngSwitchDefault>Guest</p>
</div>
role = 'user';

When to use: To dynamically render elements, lists, or conditional content.

2.3 Attribute Directives

  • Definition: Attribute directives change the appearance or behavior of an element without changing its structure.
  • Built-in Angular attribute directives:
  1. ngClass – Adds/removes CSS classes dynamically.
  2. ngStyle – Adds/removes inline styles dynamically.
  3. ngModel – Two-way data binding for form controls.

2.3.1 ngClass Example

<p [ngClass]="{'highlight': isActive}">Hello Angular!</p>
<button (click)="toggle()">Toggle Highlight</button>
isActive = false;

toggle() {
this.isActive = !this.isActive;
}
.highlight {
color: white;
background-color: blue;
}

2.3.1 ngStyle Example

<p [ngStyle]="{'font-size.px': fontSize, 'color': color}">
Style me dynamically!
</p>
<button (click)="increaseFont()">Increase Font</button>
fontSize = 14;
color = 'black';

increaseFont() {
this.fontSize += 2;
}

2.3.3 Custom Attribute Directive Example

You can create your own directive to change the background color on hover.

// highlight.directive.ts
import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@Input() appHighlight = 'yellow';

constructor(private el: ElementRef) {}

@HostListener('mouseenter') onMouseEnter() {
this.el.nativeElement.style.backgroundColor = this.appHighlight;
}

@HostListener('mouseleave') onMouseLeave() {
this.el.nativeElement.style.backgroundColor = '';
}
}
<p appHighlight="lightgreen">Hover over me!</p>

When to use: To create reusable behavior that can be applied to multiple elements (like hover effects, tooltips, dynamic styles).

3. Key Concepts for Directives

  1. @Directive Decorator: All custom directives require this decorator.
  2. ElementRef: Gives access to the DOM element.
  3. Renderer2: Safely manipulate the DOM without directly touching it.
  4. HostListener: Listen to DOM events like click, mouseenter, mouseleave.
  5. Inputs in Directives: Make the directive reusable and configurable.

--

--

Written by Wali Muhammad

Consultant Frontend Developer