Menu
Nadzweb.com
Nadzweb.com

Angular2 – writing custom pipe

Posted on June 27, 2016July 27, 2016 by admin

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! 🙂

  • angular2
  • angular2-pipes
  • Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *

    *
    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

    Tags

    .htaccess angular angular2 angular2-pipes angular4 angularjs apache bigdata blockchain children codeigniter computer graphics ethereum flot flot charts funny hadoop http javascript jquery kanban lena linux love math mathematics microsoft misc node js php phpframework php frameworks postgres pun-intended python react sass scrum scss silverstripe software ssl story valentines day wordpress

    Archives

    Recent Posts

    • Install only Postgres client 11 on Ubuntu 18.04
    • PostgreSQL – Granting access to users
    • Querying JSONB Postgres fields in SQLAlchemy
    • Angular – Writing unit tests for setTimeout in functions
    • Angular 6 – getting previous url from angular router
    ©2021 Nadzweb.com | Powered by WordPress & Superb Themes