Angular course · Module 14: Advanced Patterns

Custom Pipes

2 min read ·
In this lesson4

Pipes transform data in templates - like a master craftsman polishing a sword blade.

Simple Pipe

@Pipe({
  name: 'truncate',
  standalone: true
})
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit = 50, trail = '...'): string {
    if (!value) return '';
    if (value.length <= limit) return value;
    return value.substring(0, limit) + trail;
  }
}

// Usage
<p>{{ longText | truncate }}</p>
<p>{{ longText | truncate:100:'...' }}</p>

Pipe with Dependency Injection

@Pipe({
  name: 'relativeTime',
  standalone: true
})
export class RelativeTimePipe implements PipeTransform {
  private locale = inject(LOCALE_ID);

  transform(value: Date | string): string {
    const date = new Date(value);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMins < 1) return 'just now';
    if (diffMins < 60) return `${diffMins} min ago`;
    if (diffHours < 24) return `${diffHours} hours ago`;
    if (diffDays < 7) return `${diffDays} days ago`;

    return date.toLocaleDateString(this.locale);
  }
}

Async Pipe Alternative

@Pipe({
  name: 'safeAsync',
  standalone: true,
  pure: false  // Impure - checks on every change detection
})
export class SafeAsyncPipe implements PipeTransform, OnDestroy {
  private subscription?: Subscription;
  private latestValue: any = null;

  transform<T>(obs: Observable<T>, defaultValue: T): T {
    if (!this.subscription) {
      this.subscription = obs.subscribe(value => {
        this.latestValue = value;
      });
    }
    return this.latestValue ?? defaultValue;
  }

  ngOnDestroy(): void {
    this.subscription?.unsubscribe();
  }
}

// Usage
<p>{{ data$ | safeAsync:'Loading...' }}</p>

Filter Pipe

@Pipe({
  name: 'filter',
  standalone: true
})
export class FilterPipe implements PipeTransform {
  transform<T>(items: T[], predicate: (item: T) => boolean): T[] {
    if (!items || !predicate) return items;
    return items.filter(predicate);
  }
}

// Usage with function
<div *ngFor="let samurai of samuraiList | filter:isActive">
  {{ samurai.name }}
</div>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the difference between a pure and an impure pipe?

  2. 2. Which interface must a pipe class implement, and which method does it enforce?

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the expression that calls the truncate pipe with a limit of 100 in a template (one line, left to right):

  • Code editor

    Complete the custom pipe that truncates text to a given length.

  • Click in order

    Click the elements in order to build the start of the pipe decorator: @Pipe({

  • Vertical ordering

    Order the lines of the truncate pipe definition (top to bottom):

  1. QuestionPure vs Impure Pipe
  2. QuestionPipe interface
  3. Put in orderUsing a pipe with a parameter
  4. Coding taskPractice: Custom Pipe
  5. Click in orderBuilding the @Pipe decorator
  6. Put in orderPipe class definition

Useful articles