How to generate a pipe in Angular

Generating Angular pipes enables you to create reusable data transformation logic for templates, providing clean and consistent formatting across your application. As the creator of CoreUI, a widely used open-source UI library, I’ve generated numerous Angular pipes for date formatting, text transformation, and number formatting in enterprise applications. From my expertise, the most efficient approach is to use Angular CLI’s generate pipe command. This method creates the proper pipe structure, implements the PipeTransform interface, and generates test files while following Angular best practices.

Use ng generate pipe command to create a new Angular pipe with proper structure and PipeTransform interface.

# Generate a basic pipe
ng generate pipe truncate
# or shortened
ng g p truncate

# Generate pipe in specific folder
ng generate pipe shared/pipes/truncate
// truncate.pipe.ts (generated file)
import { Pipe, PipeTransform } from '@angular/core'

@Pipe({
  name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit = 50, trail = '...'): string {
    if (!value) return ''

    return value.length > limit
      ? value.substring(0, limit) + trail
      : value
  }
}
<!-- Usage in component template -->
<p>{{ longText | truncate:30:'...' }}</p>
<span>{{ user.bio | truncate:100 | titlecase }}</span>
// Don't forget to declare pipes in module
import { NgModule } from '@angular/core'
import { TruncatePipe } from './pipes/truncate.pipe'

@NgModule({
  declarations: [TruncatePipe],
  exports: [TruncatePipe]
})
export class SharedModule {}

Angular CLI’s ng generate pipe command creates a pipe class that implements the PipeTransform interface with a required transform method. Pipes are pure by default, which optimizes performance by only executing when input changes. Use impure pipes sparingly as they execute on every change detection cycle. Pipes can accept multiple parameters and can be chained together for complex transformations.

Best Practice Note:

This is the same approach we use for generating pipes in CoreUI Angular applications for consistent data formatting and transformation.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to sleep in Javascript
How to sleep in Javascript

How to Migrate from create-react-app to Vite?
How to Migrate from create-react-app to Vite?

How to Remove Underline from Link in CSS
How to Remove Underline from Link in CSS

JavaScript printf equivalent
JavaScript printf equivalent

Answers by CoreUI Core Team