0
0
Angularframework~5 mins

Standalone pipes and directives in Angular

Choose your learning style9 modes available
Introduction

Standalone pipes and directives let you use them without adding to a module. This makes your code simpler and easier to manage.

You want to create a small reusable pipe or directive without making a module.
You want to share a pipe or directive directly in a component.
You want faster development by avoiding module setup for simple features.
You want to keep your app structure clean and modular.
You want to use Angular's new standalone component system fully.
Syntax
Angular
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'examplePipe',
  standalone: true
})
export class ExamplePipe implements PipeTransform {
  transform(value: string): string {
    return value.toUpperCase();
  }
}

import { Directive } from '@angular/core';

@Directive({
  selector: '[exampleDirective]',
  standalone: true
})
export class ExampleDirective {
  // directive logic here
}

Use standalone: true in the decorator to make a pipe or directive standalone.

Standalone pipes and directives can be imported directly into components.

Examples
This standalone pipe reverses a string.
Angular
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'reverseText',
  standalone: true
})
export class ReverseTextPipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}
This standalone directive highlights an element with yellow background.
Angular
import { Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive({
  selector: '[highlight]',
  standalone: true
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
  }
}
Sample Program

This standalone component uses the standalone pipe and directive directly without a module. The text 'hello' is reversed and the heading is highlighted.

Angular
import { Component } from '@angular/core';
import { ReverseTextPipe } from './reverse-text.pipe';
import { HighlightDirective } from './highlight.directive';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ReverseTextPipe, HighlightDirective],
  template: `
    <h1 highlight>{{ 'hello' | reverseText }}</h1>
  `
})
export class AppComponent {}
OutputSuccess
Important Notes

Standalone pipes and directives simplify Angular app structure by removing the need for NgModules.

Remember to add standalone pipes and directives to the imports array of the component using them.

This feature requires Angular 14 or later.

Summary

Standalone pipes and directives work without modules.

Use standalone: true in their decorators.

Import them directly into components for easy reuse.