🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
HTML MASTER CLASS /// LEARN TAGS /// BUILD STRUCTURE /// SEMANTIC WEB /// HTML MASTER CLASS /// LEARN TAGS ///

Directives Intro in Angular

Learn the taxonomy of Angular directives and understand the fundamental differences between components, structural markers, and attribute modifiers.

Total XP: 0|💻 angular XP: 0

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

Select an unlocked node to view details root

🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.

Directives are the special markers in your HTML that tell Angular to attach specific behavior to DOM elements or even transform the DOM structure entirely.

1The Directive Trinity

Angular categorizes directives into three types. First, Components are the most common; they manage a specific patch of screen. Second, Structural Directives (*ngIf, *ngFor) are the architects; they physically add or remove elements from the DOM. Third, Attribute Directives ([ngClass], [ngStyle]) are the decorators; they modify the attributes and styles of existing elements without changing the structure.

2Asterisk vs Brackets

The syntax of a directive tells you its purpose. An asterisk (*) like in *ngIf indicates that the directive is structural and will use a <ng-template> behind the scenes to manage the layout. Square brackets [] like in [ngClass] indicate that the directive is an attribute directive, treating the directive name as a property of the host element.

3Step-by-Step Breakdown

Directives are one of the most powerful features of Angular. They allow you to extend the capabilities of HTML and create custom behaviors for your elements.

In Angular, there are three main types of directives: Components, Structural Directives, and Attribute Directives.

Components are technically directives! They are directives that have a template. Whenever you see a custom tag like <app-user>, that's a component directive.

Checkpoint: True or False? An Angular Component is technically a type of Directive.

  • True
  • False

Structural directives change the DOM structure by adding or removing elements. They are easy to spot because they always start with an asterisk (*).

Attribute directives change the appearance or behavior of an existing element. They use square brackets [] just like property binding.

Checkpoint: Which type of directive is used to add or remove elements from the DOM (like *ngIf)?

  • Attribute Directive
  • Structural Directive
  • Component Directive

Think of directives as 'Instructions' for Angular. You're telling the framework exactly how to render and manipulate the page.

Ready to go deeper? Next, we'll master the most common structural directives: *ngIf and *ngFor.

Level Up 🚀

Advanced cheat sheets, SEO tricks, and interview prep for this topic.

Browser Support

ChromeSupported

Fully supported.

FirefoxSupported

Fully supported.

SafariSupported

Fully supported.

EdgeSupported

Fully supported.

Accessibility (A11y)

1Structural Directives Genuinely Remove Elements, Which Is Good for Screen Readers

`*ngIf` removes its host element from the DOM entirely rather than just hiding it visually — unlike a CSS `display: none` mistake left as `visibility: hidden`, this guarantees hidden content is never confusingly reachable by keyboard tab order or screen reader virtual cursor.

2The Three Categories of Directives Map to Three Different Accessibility Concerns

Components (templates) need semantic HTML, attribute directives (behavior) need proper keyboard/ARIA handling, and structural directives (DOM shape) need to be used so that conditional content doesn't leave stray empty containers confusing the accessibility tree.

SEO Implications

  • 1

    `*ngIf` Content Only Exists in the DOM When the Condition Is True — Including for Crawlers

    Content conditionally rendered with `*ngIf` isn't present in the DOM at all when false, even under server-side rendering — if content should be crawlable, the condition driving it must resolve to true during the server render, not just eventually in the browser.

  • 2

    Directives Don't Change a Page's Fundamental Crawlability, Rendering Strategy Does

    Whether a page uses zero or a hundred directives is irrelevant to SEO in isolation — what matters is whether the resulting DOM (after all directives resolve) is present in server-rendered HTML, which depends on Angular Universal/prerendering, not directive usage itself.

Best Practices

Use `*ngIf` for Content That Should Genuinely Not Exist When Hidden

Reserve `[hidden]` or CSS-based show/hide for cases where you want to preserve component state while visually hiding it; use `*ngIf` when the content should be fully destroyed and recreated, avoiding wasted memory and stale state for content that's rarely shown.

Avoid Complex Logic Directly in Structural Directive Expressions

`*ngIf="user && user.roles.includes('admin') && !isLoading"` is hard to read and re-evaluates on every check — extract it into a named getter or computed property with a clear name instead.

Frequent Bugs

THE BUG

Content wrapped in `*ngIf` seems to reset its internal state every time the condition becomes true again.

THE FIX

This is actually expected behavior, not a bug — `*ngIf` destroys and recreates the component/element from scratch each time the condition toggles. If state needs to persist across toggles, use `[hidden]` or a CSS-based show/hide instead, which keeps the component instance alive.

THE BUG

Two structural directives are applied to the same host element and Angular throws a template error.

THE FIX

Only one structural directive (`*ngIf`, `*ngFor`, `*ngSwitchCase`, etc.) can be applied directly to a single element at a time, since each expands to its own wrapping `<ng-template>`. Nest them on separate wrapping elements, or use `<ng-container>` to add an extra grouping layer without an extra real DOM node.

Real-World Examples

Conditional Rendering With Nested Structural Directives

A user list conditionally shows a loading state, an empty state, or the actual list, using nested `<ng-container>` elements to apply multiple structural directives without adding extra wrapping DOM nodes.

<ng-container *ngIf="!isLoading; else loadingTpl">
  <ng-container *ngIf="users.length; else emptyTpl">
    <li *ngFor="let user of users">{{ user.name }}</li>
  </ng-container>
</ng-container>

Interview Prep

?Frequently Asked Questions

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Common Pitfalls & Errors

The Error //

Memory leaks from unclosed Subscriptions

// Wrong ngOnInit() { this.dataService.getData().subscribe(data => this.data = data); } // Correct ngOnInit() { this.sub = this.dataService.getData().subscribe(data => this.data = data); } ngOnDestroy() { if (this.sub) this.sub.unsubscribe(); }

The Solution //

When subscribing to Observables in a component, always unsubscribe in the ngOnDestroy hook to prevent memory leaks.

The Error //

Directly manipulating the DOM

// Wrong document.getElementById('my-el').style.color = 'red'; // Correct @ViewChild('myEl') myEl: ElementRef; this.renderer.setStyle(this.myEl.nativeElement, 'color', 'red');

The Solution //

Avoid using document.getElementById or native DOM APIs. Use Angular's templating, bindings, and tools like Renderer2 or ViewChild.

Lesson Glossary

[01]Directive

A marker on a DOM element that tells Angular to attach behavior or transform the DOM.

Code Preview
Marker

[02]Structural Directive

A directive that changes the DOM layout by adding and removing elements.

Code Preview
*ngIf

[03]Attribute Directive

A directive that changes the appearance or behavior of an element, component, or another directive.

Code Preview
[ngClass]

[04]Component Directive

A directive with an associated template; the most common directive type.

Code Preview
@Component

[05]ng-template

An Angular element used for rendering HTML that isn't displayed by default, used by structural directives.

Code Preview
<ng-template>

[06]Selector

The attribute name or CSS selector used to apply a directive to an element.

Code Preview
Target

Continue Learning