Angular2 Explode Pipe

I am busy writing my first pipe for Angular2 and I need some help putting this together.

The problem:
I have an api returning a set of numbers: 1-2-03-4-5 and I would like to style these numbers like so:

<div class="number">1</div>
<div class="number">2</div>
<div class="number">03</div>
<div class="number">4</div>
<div class="number">5</div>

If this where PHP I wold simply go:

$array = explode("-","1-2-03-4-5");
foreach ($array AS $number) {
    echo ' <div class="number">'.$number.'</div>';

My aim is to do this sort of thing in angular so I have created a pipe:

import {Pipe} from "angular2/core";

export class ExplodePipe {
    transform(value) {
        return some explody stuff here;

This is included in my component

import {Component, OnInit} from 'angular2/core';
import {RouteParams, ROUTER_DIRECTIVES} from "angular2/router";
import {HelpMenuComponent} from "./help-menu.component";
import {ExplodePipe} from "../Pipes/my.pipes";


    template: `
        {{ExplodeMe | explode}}


export class ViewResultsComponent implements OnInit {
ExplodeMe: “1-2-03-4-5”;

  1. Where would I insert the HTML to be included in the output? Would this be in the pipe method? Can I somehow tell the pipe to format in a certain way from the {{}} part?
  2. What data is made available to the pipe how do I access it?


Leave a Reply

2 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
newest oldest most voted
Notify of

So I thought I would post my final solution. This essentially does exactly what PHP explode does and is very useful! My pipe: import {Pipe} from "angular2/core"; import {InvalidPipeArgumentException} from "angular2/src/common/pipes/invalid_pipe_argument_exception"; import {isString, isBlank} from "angular2/src/facade/lang"; @Pipe({ name:"explode" }) export class ExplodePipe { transform(value, key) { if (!isString(key)) { key = '-'; } if (isBlank(value)) return value; if (!isString(value)) { throw new InvalidPipeArgumentException(ExplodePipe, value); } return value.split(key); } } And using the pipe in my html code: Split some string: 1-2-3-4-5 {{SomeString | explode:'-'}} or simply: {{SomeString | explode}} since '-' is default Split some string: 1*2*3*4*5 {{SomeString | explode:'*'}}… Read more »


Pipes are used to take data as input, and to transform it as output. The implementation of the transformation function is up to you. But keep in mind that the output still needs to be data (it cannot contain HTML). I suggest that you create a Pipe that takes a string and returns an array, using a dash as the split delimiter: @Pipe({ name:"explode" }) export class ExplodePipe { transform(value) { return value.split('-'); } } Use the Pipe in an *ngFor expression to loop over the items and format each item in a div: @Component({ selector: 'app', pipes: [ExplodePipe] template:… Read more »