Directives in Angular

basic · Angular

he DOM Manipulation Engine Directives are a foundational structural mechanism used to extend the capabilities of standard HTML templates. While data binding allows you to sync values, directives allow you to manipulate the behavior, styling, or structural layout of the Document Object Model (DOM) dynamically. Architecturally, directives are divided into three primary categories: Component Directives: Components are technically directives wrapped inside a physical HTML template. Attribute Directives: Change the appearance or baseline behavior of an existing element without modifying the structural tree layout (e.g., ngClass or ngStyle ). Structural Directives: Completely alter the layout shape of the DOM by conditionally adding, removing, or duplicating entire HTML elements and their children. They are traditionally prefixed with an asterisk ( * ) in legacy syntax, or declared via native modern blocks ( @ ). Conditional Structural Rendering: ngIf / @if The ngIf directive evaluates a boolean expression to determine whether a block of HTML markup should be compiled and inserted into the active DOM tree, or completely stripped out of existence. The Core Distinction: Unlike hiding elements using CSS parameters (like display: none ), ngIf destroys the element entirely when the condition is false. This unmounts the component instance, releases component memory, and cleans up active event bindings. The Modern Alternative: Modern frameworks favor native block conditional syntax ( @if ) over the legacy attribute directive ( *ngIf ) because it yields better performance and cleaner formatting templates. HTML @if (isLaunching) { <div class="status-banner">Platform launching soon!</div> } @else if (hasError) { <div class="error-banner">Failed to load dependencies.</div> } @else { <div class="status-banner">Welcome to the Dashboard</div> } < div * ngIf = "isLaunching" class = "status-banner" > Platform launching soon! </ div > List Iteration and Loop Scaling: ngFor / @for The ngFor directive loops over a collection of data properties (like an array of items or objects) to dynamically generate repeating sets of identical HTML templates on screen. Tracking and Performance Efficiency: When list values change or update, iterating engines need to know exactly which elements were modified to prevent re-rendering the entire list from scratch. The Optimization Metric: Legacy structures use a trackBy function parameter, while modern block iterations strictly enforce a built-in track property expression. This assigns a unique identifier (like a database ID) to every node, allowing the framework to modify only the specific DOM node that altered. HTML <div class="job-container"> @for (job of jobListings; track job.id) { <div class="job-card"> <h4>{{ job.title }}</h4> <p>{{ job.company }}</p> </div> } @empty { <p>No handpicked jobs matching your search criteria were found.</p> } </div> <div *ngFor="let job of jobListings; trackBy: trackJobById" class="job-card"> <h4>{{ job.title }}</h4> </div> Multi-Branch Matching Layouts: ngSwitch / @switch The ngSwitch directive handles multi-branch conditional rendering. It is utilized when you need to evaluate an expression against a variety of distinct structural layout states, functioning exactly like a standard JavaScript or TypeScript switch statement inside the view layer. Operational Mechanics: It matches a target value against specific string or numeric cases. When a match is verified, it renders the corresponding layout block and strips out all non-matching sibling cases. HTML <div class="profile-badge"> @switch (currentUserRole) { @case ('Admin') { <span class="badge-red">System Administrator</span> } @case ('Mentor') { <span class="badge-blue">Verified Mentor</span> } @default { <span class="badge-gray">Registered Student</span> } } </div> <div [ngSwitch]="currentUserRole"> <span *ngSwitchCase="'Admin'" class="badge-red">System Administrator</span> <span *ngSwitchCase="'Mentor'" class="badge-blue">Verified Mentor</span> <span *ngSwitchDefault class="badge-gray">Registered Student</span> </div> Structural Syntax Evolution Summary Metric Legacy Directive Syntax ( *ngIf , *ngFor ) Modern Block Syntax ( @if , @for ) Import Requirements Must explicitly import CommonModule or individual directives into standalone components. Core primitive syntax; built directly into the compiler with zero imports required . DOM Overhead Requires wrapping nested conditions in auxiliary elements like <ng-container> . Uses a native structural syntax wrapper, removing clean-up tag overhead. Performance Profile Relies heavily on internal directive orchestration hooks during runtime execution cycles. Optimizes compilation loops directly, resulting in faster execution pipelines. List Empty States Demanded writing a completely secondary container paired with an explicit length checking conditional. Features a built-in @empty fallback block that handles zero-length arrays natively.

Back to Angular

Browse all study material on Careeroza