Custom Pipes

We have used pipes before for transforming data. For example, we have uses pipes to convert text into upper case.

A pipe is simply an object that has a transform function. We can write our own pipes very easily. This is a simple pipe that receives a value, and prepends it with the word "toast"

var ToastPipe = ng.core
.Pipe({
name:'toast'
})
.Class({
constructor: function() {},
transform: function(value) {
return "Toast " + value
}
})

We would make use of it like this:

var AppComponent = ng.core
.Component({
selector: "app",
pipes: [ToastPipe],
template:
`
{{"hello" + "world" | toast}}
`
})
.Class({
constructor: function() {}
})

Notice that we have to tell our template we want to use it by passing a pipes attribute.

Exercise - Reversing a String

We can reverse a string by using code a little like this:

"abc".split('').reverse().join('');

Write a pipe that will reverse an string, so I can say hello | reverse and it will output olleh

Harder Exercise - Sort Filter

I have an array of people like this:

[
{
name: "Hairy Margo",
age: 43
},
{
name: "Snake-eye Sammy",
age: 9
},
{
name: "Manchego McGraw",
age: 68
}
]

I would like to be able to sort these people by name.

Write a filter that accepts an array like this and sorts it by the name attribute. You may wish to read up on the array sort method on MDN

Use ngFor to output the sorted filter.

Extra difficult extension

Parameterise the filter, so you can choose which attribute to sort on.

Now add buttons to the page, so that you can click them to sort on different attributes.

comments powered by Disqus