ReviseAlgo Logo

Fundamentals

Directives

Master Angular Directives, covering structural directives (*ngIf, *ngFor, trackBy), attribute directives (ngClass, ngStyle), and custom directives.

Last Updated: July 15, 2026 • 12 min read

1. Learning Objectives

In this lesson, you will master Angular directives. By the end of this topic, you will be able to:

  • Differentiate between structural and attribute directives.
  • Use structural directives (*ngIf, *ngFor, *ngSwitch) to modify the DOM layout.
  • Optimize list rendering performance by implementing trackBy functions.
  • Apply dynamic styles and CSS classes using ngClass and ngStyle.
  • Build custom attribute directives using the @Directive decorator.

2. Overview

Directives are classes that add new behavior or modify styles and structures of elements in the DOM. Angular separates them into structural directives (which add, remove, or replace DOM elements) and attribute directives (which update the appearance or behavior of existing elements).

3. Why This Topic Matters

Using directives correctly is important for DOM performance and preventing memory leaks:

  • Slow Lists without trackBy: By default, when a list array changes, *ngFor redraws all elements in the list. For large lists, this causes lag. Implementing a trackBy function helps Angular identify which elements changed, updating only those specific DOM nodes.
  • Multiple Structural Directives Error: Placing more than one structural directive (e.g. using both *ngIf and *ngFor) on a single HTML tag will throw a template parsing error. You must wrap the element or use container tags to nesting directives.

4. Real-World Analogy

Think of directives like **a stage coordinator managing a theater play**:

  • Structural Directives (Stage Manager): Decides who is on stage. The manager places actors in the scene (*ngIf) or duplicates prop boxes on stage (*ngFor), modifying the actual layout of the set.
  • Attribute Directives (Wardrobe Stylist): Does not add or remove actors, but updates their appearance. The stylist changes an actor's shirt color (ngStyle) or applies a name tag (ngClass) to their costume.

5. Core Concepts

Angular directives are grouped into three categories:

  • Structural Directives (*ngIf, *ngFor): Modify the DOM layout. They use an asterisk (*) prefix, which is shorthand for wrapping the element in an <ng-template> tag.
  • Attribute Directives (ngClass, ngStyle): Modify the appearance or behavior of DOM elements. Bound using square brackets ([ngClass]).
  • Custom Directives: User-defined classes decorated with @Directive that inject ElementRef and Renderer2 to modify element attributes or handle event interactions.
Directive Type Syntax Format DOM Impact
Structural *ngIf="condition" Adds or removes the element from the DOM tree.
Attribute [ngClass]="{'active': isTrue}" Modifies the classes or styles of an existing element.

6. Syntax & API Reference

Below is a custom directive that changes an element's background color on hover:

7. Visual Diagram

This diagram displays how directives modify DOM elements:

8. Live Example — Full Working Code

Below is a standalone component that showcases structural lists (using trackBy) and dynamic styling classes:

9. Interactive Playground

Try It Yourself Challenges:

  1. Change the task list items status to completed dynamically and notice how ngClass updates the layout.
  2. Test what happens when you remove the trackBy property from the loop statement.

10. Common Mistakes

Mistake Why it happens Wrong Correct
Multiple structural directives on one element Placing more than one structural directive (like *ngIf and *ngFor) on a single HTML tag, triggering a parser error. <li *ngIf="showItems" *ngFor="let item of items"> Wrap the loop in an <ng-container *ngIf="showItems">.
Omitting the asterisk prefix Forgetting the asterisk (*) prefix on structural directives, causing them to be parsed as standard attributes. <div ngIf="visible"> <div *ngIf="visible">

11. Best Practices

  • Always implement trackBy with *ngFor: Use trackBy functions for all dynamic lists to optimize DOM rendering performance.
  • Use ng-container to avoid extra wrapper tags: Use <ng-container> when grouping elements for structural directives. This groups elements without rendering extra wrapper div tags in the final HTML.
  • Use Renderer2 for DOM updates: When building custom directives, use Angular's Renderer2 instead of modifying el.nativeElement directly. This keeps the code platform-safe (supporting server-side rendering).

12. Browser Compatibility/Requirements

Directives are compiled to standard JavaScript DOM manipulation instructions. Renderer2 ensures compatibility with all platforms, including server-side rendering (SSR) environments.

13. Interview Questions

🟢 Q1: Why is it important to use a trackBy function with *ngFor?

Answer: Without trackBy, if the list array changes, Angular redraws all DOM nodes in the list. When you provide a trackBy function, Angular uses unique identifiers (like task IDs) to track elements. When the array changes, Angular updates, moves, or deletes only the specific DOM nodes that changed, improving performance.

14. Debugging Exercise

Identify and fix the compiler error in this template fragment:

View Solution

Diagnosis: The list element (<li>) has two structural directives (*ngIf and *ngFor) declared on it. Angular does not support placing multiple structural directives on a single element. To fix this, wrap the loop in an <ng-container> tag and apply the conditional directive there.

Fixed template markup:

15. Practice Exercises

Exercise 1: Create a conditional visibility banner

Build a component template that uses `*ngIf` to toggle the visibility of an alert banner when a button is clicked. Use `ngClass` to style the banner (e.g. green for success, red for errors).

16. Scenario-Based Challenge

The Large List Performance Challenge:

Your application displays a live feed of 1,000 real-time stock ticker values. Every second, the feed updates, causing the UI to freeze due to redrawing list elements. Write a template implementation using *ngFor and a trackBy function to optimize list rendering.

17. Quick Quiz

Q1: Which element is used to group elements without rendering extra tags in the final HTML DOM?

A) <div>

B) <ng-container>

C) <ng-template>

Answer: B — The <ng-container> tag groups elements without rendering extra wrappers in the DOM.

18. Summary & Key Takeaways

  • • Structural directives modify the DOM layout, while attribute directives update the appearance or behavior of existing elements.
  • • Use trackBy functions with *ngFor to optimize list rendering and prevent unnecessary DOM redraws.
  • • Avoid placing multiple structural directives on a single element; use ng-container to group nested directives.

19. Cheat Sheet

Directive Example Syntax
*ngFor <li *ngFor="let item of items; trackBy: trackById">
---