Chapter 6: Pipes Built-in Pipes (Currency, Date, etc.) Custom Pipes & Pipe Chaining

Chapter 6: Pipes Built-in Pipes (Currency, Date, etc.) Custom Pipes & Pipe Chaining

AI Reading

Quick summary of this article

Angular directives are classes that add behavior to DOM elements, enabling dynamic and reusable user interfaces. The chapter covers three types: component directives (with templates), structural directives (like *ngIf and *ngFor) that change DOM layout, and attribute directives (like [ngClass]) that modify element appearance or behavior. It also explains how to create custom attribute and structural directives, with best practices for keeping templates clean and code modular.

  • Built-in structural directives include *ngIf for conditional rendering and *ngFor for looping over collections.
  • [ngClass] dynamically applies CSS classes based on conditions, such as { 'active': isActive, 'disabled': !isActive }.
  • Custom attribute directives (e.g., appHighlight) use @HostListener and Renderer2 to respond to events like mouseenter/mouseleave.
  • Custom structural directives (e.g., appUnless) use TemplateRef and ViewContainerRef to control whether content is rendered in the DOM.
  • Best practices include using built-in directives for common tasks and creating custom ones to keep templates clean and behavior reusable, while preferring Renderer2 for safe DOM manipulation.

Chapter 5: Directives in Angular

Angular directives are powerful tools that let you manipulate the DOM and extend HTML behavior. This chapter focuses on both built-in directives and creating your own custom ones for dynamic and reusable UI components.

What Are Directives?

Directives are classes in Angular that allow you to attach behavior to elements in the DOM. There are three types:

  • Component Directives – With templates
  • Structural Directives – Change the DOM layout (e.g., *ngIf, *ngFor)
  • Attribute Directives – Change the appearance or behavior of elements (e.g., [ngClass])

Built-in Structural Directives

*ngIf

Used to conditionally render elements:


<div *ngIf="isLoggedIn">
  Welcome back!
</div>
  

*ngFor

Used to loop over a collection:


<ul>
  <li *ngFor="let user of users">{{ user.name }}</li>
</ul>
  

Built-in Attribute Directive: [ngClass]

[ngClass] lets you dynamically apply CSS classes based on conditions:


<div [ngClass]="{ 'active': isActive, 'disabled': !isActive }">
  Button
</div>
  

Creating Custom Attribute Directive

Step 1: Create Directive


ng generate directive highlight
  

Step 2: Add Logic


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

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
  }
}
  

This directive changes background color on mouse events. Use it like:


<p appHighlight>Hover to highlight me!</p>
  

Creating Custom Structural Directive

Step 1: Generate the Directive


ng generate directive unless
  

Step 2: Implement Structural Behavior


import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appUnless]'
})
export class UnlessDirective {
  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}

  @Input() set appUnless(condition: boolean) {
    if (!condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }
}
  

This directive renders content only if the condition is false — opposite of *ngIf.


<div *appUnless="isLoggedIn">
  You must log in first.
</div>
  

Best Practices

  • Use *ngIf and *ngFor to conditionally render DOM elements.
  • Use [ngClass] or [ngStyle] for dynamic styles.
  • Create custom directives to keep templates clean and behavior reusable.
  • Prefer Renderer2 for DOM manipulation to ensure compatibility.

Conclusion

Directives are essential to building dynamic UIs in Angular. Whether you use built-in options or create custom ones, mastering directives will elevate your frontend development skills and keep your code modular and expressive.

Next Steps

In Chapter 6, we’ll dive into Angular Pipes — a powerful way to transform and format data directly within templates.

Leave a Reply

Your email address will not be published. Required fields are marked *