Home » Featured, Headline, Software Development

Angular2 – writing custom pipe

27 June 2016 No Comment

Pipes are important for data transformations within a template.
Below is a custom pipe for Angular2 which transforms any string to a standard slug.

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

@Pipe({name: 'slug'})
export class SlugPipe implements PipeTransform {
  transform(str: string): string {
    return str.toString().toLowerCase()
      .replace(/\s+/g, '-')     // Replace spaces with -
      .replace(/[^\w\-]+/g, '') // Remove all non-word chars
      .replace(/\-\-+/g, '-')   // Replace multiple - with single -
      .replace(/^-+/, '')       // Trim - from start of text
      .replace(/-+$/, '');
  }

}

Usage:

Usage in Angular2 Templates.

let name = 'My big Long >> name'; 
{{ name | slug }}
// output:: my-big-long-name

Usage in Angular2 Components.

let name = 'My big Long >>""" name ';
let slugify = new SlugPipe();

let mySlugName = slugify.transform(name); // output:: my-big-long-name

Hope this is beneficial to the readers! 🙂

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image