Creating an Angular Pipe - Truncate Text

Published on

A common string manipulation operation that I do quite often in Angular templates is to truncating long text to specific length with an ellipsis. From what I’ve found there currently isn’t a truncate pipe built into Angular. The closest thing I’ve found is the SlicePipe which could be used in replacment of this pipe but doesn’t have a suffix option.

The code snippet below is my current solution for a truncate pipe with options for length and suffix.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'fooTruncate',
})
export class FooTruncatePipe implements PipeTransform {
  public transform(value: string, length: number | null, suffix: string = '...'): string {
    const truncationLength: number = length ?? 300;
    return value.length > truncationLength
      ? `${value.slice(0, Math.ceil(truncationLength)).trim()}${suffix}`
      : value;
  }
}

The default truncation length is 300 with a default suffix of ‘…’. If no arguments are passed along to the pipe, these default values will be used. You can specify the length and suffix by passing arguments along with the value to truncate.

Some examples of this pipe being used can be seen below…

<!-- Using default truncation length and suffix -->
<p>{{ someSuperLongParagraphText | fooTruncate }}</p>

<!-- Using default truncation suffix with a specified length -->
<p>{{ someSuperLongParagraphText | fooTruncate: 120 }}</p>

<!-- Using specific truncation length and suffix -->
<p>{{ someSuperLongParagraphText | fooTruncate 120:'.....' }}</p>

<!-- Using default truncation length and specified suffix -->
<p>{{ someSuperLongParagraphText | fooTruncate null:'.....' }}</p>

 

Hope this was helpful!

comments powered by Disqus