Pipe is a transformer to display data. You can use pipes for string formatting, data converting or other things. Pipes let you separate view-specific logic from components or services.
In Angular 2, you can use pipes with pipe operator (|
) in the component template. Let’s look at the following simple example:
@
Component
({
selector
:
'my-cmp'
,
template
:
`
<
h1
>
{{
title
|
uppercase
}}
<
/h1>`,
})
export
class
MyComponent
{
title
=
'Pipes'
;
}
The component will be rendered as <h1>PIPES</h1>
. In this case, title
property is transformed by the uppercase
pipe. All pipes take an input value from the left-side of the operator (|
), and some pipes take additional parameters from the right-side of the pipe’s name as pipe:param1:param2
like the following code:
@
Component
({
selector
:
'my-cmp'
,
template
:
`
{{
text
|
replace
:
'World'
:
'Angular'
}}
`
,
// -> Hello Angular
})
export
class
MyComponent
{
text
=
'Hello World'
;
}
A reason of the name, pipe, is that supports chained transforming like data streams. You can use multiple pipes at the same input.
@
Component
({
selector
:
'my-cmp'
,
template
:
`
{{
text
|
replace
:
'World'
:
'Angular'
|
lowercase
}}
`
,
// -> hello angular
})
export
class
MyComponent
{
text
=
'Hello World'
;
}
By default, many useful built-in pipes are provided and you can use them without explicit importing. Ok, let’s figure them out by its kind.
First, let’s figure out about pipes transforming string to string.
UpperCasePipe
transforms a string to an upper-cased string. It’s named uppercase
.
@
Component
({
selector
:
'my-cmp'
,
template
:
`
{{
'Angular 2'
|
uppercase
}}
`
// -> 'ANGULAR 2'
})
export
class
MyComponent
{
}
Similarly, LowerCasePipe
makes a string lower-cased. It’s named lowercase
.
@
Component
({
selector
:
'my-cmp'
,
template
:
`
{{
'Angular 2'
|
lowercase
}}
`
// -> 'angular 2'
})
export
class
MyComponent
{
}
ReplacePipe
returns a string replaced with a given pattern. replace
pipe takes two parameters as replace:pattern:replacement
.
@
Component
({
selector
:
'my-cmp'
,
template
:
`
{{
'Hello AngularJS!'
|
replace
:
'AngularJS'
:
'Angular 2'
}}
`
// -> 'Hello Angular 2!'
})
export
class
MyComponent
{
}
A RegExp
object can be used as a pattern
parameter.
@Component({ selector: 'my-cmp', template: `{{ 'Hello AngularJS!' | replace:ngPattern:'Angular 2' }}` // -> 'Hello Angular 2!' }) export class MyComponent { ngPattern = /angularw+/i; }
Some pipes can convert a number value to a string and format it.
DecimalPipe
formats a number as a decimal string. It is named number
and it has an optinal parameter, digitInfo
. digitInfo
is a string that has three segments like the following:
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
minIntegerDigits
is the minimum number of integer digits to use. It defaults to 1.minFractionDigits
is the minimum number of digits after fraction. It defaults to 0.maxFractionDigits
is the maximum number of digits after fraction. It defaults to 3.In other words, default digitInfo
is 1.0-3
.
See the following example:
@Component({ selector: 'my-cmp', template: ` {{ 12.3456 | number }}, {{ 12.3456 | number:'3.0-2' }}, {{ 12 | number:'3.2' }} ` // -> 12.346, 012.35, 012.00 }) export class MyComponent { }
PercentPipe
is similar to DecimalPipe
. The difference is that PercentPipe
shows a number in percentage.
@
Component
({
selector
:
'my-cmp'
,
template
:
`
{{
0.1234
|
percent
}},
{{
0.1234
|
percent
:
'3.0-2'
}},
{{
0.12
|
percent
:
'3.2'
}}
`
// -> 12.34%, 012.34%, 012.00%
})
export
class
MyComponent
{
}
CurrencyPipe
is used for displaying a number as a price. Basically it’s the same to DecimalPipe
, but CurrencyPipe
takes two additional parameters: currencyCode
and symbolDisplay
.
currencyCode
is the ISO 4217 currency code, such as “USD” for the US dollar and “EUR” for the euro.
symbolDisplay
is an optional parameter to use the currency symbol (e.g. $) or the currency code (e.g. USD) in the output. It defaults to false
.
@
Component
({
selector
:
'my-cmp'
,
template
:
`
{{
12.3456
|
currency
:
'USD'
}},
{{
12.3456
|
currency
:
'USD'
:
true
}},
{{
12.3456
|
currency
:
'USD'
:
true
:
'.0-2'
}}
`
// -> USD12.346, $12.346, $12.35
})
export
class
MyComponent
{
}
The following pipes can transform an object to a string.
JsonPipe
JsonPipe
converts an object to a string by JSON.stringify
. This pipe is useful for development.
@
Component
({
selector
:
'my-cmp'
,
template
:
`
{{
data
|
json
}}
`
// -> { "name": "foo", "value": "bar" }
})
export
class
MyComponent
{
data
=
{
name
:
'foo'
,
value
:
'bar'
};
}
DatePipe
transforms an input date value to formatted text. This pipe accepted some types as an input. The first type is a Date
type. Look at the following code:
@
Component
({
selector
:
'my-cmp'
,
template
:
`
{{
targetDate
|
date
:
'yMMMd'
}}
`
// -> Sep 3, 2015
})
export
class
MyComponent
{
targetDate
=
new
Date
(
2015
,
8
,
3
);
}
DatePipe
has an optional parameter, format
, which is used for formatting the date. The following symbols can be used in the parameter:
G
/GGGG
: era symbols corresponding to AD
/Anno Domini
y
/yy
: year symbols corresponding to 2015
/15
M
/MM
/MMM
/MMMM
: month symbols corresponding to 9
/09
/Sep
/September
d
/dd
: day symbols corresponding to 3
/03
EEE
/EEEE
: weekday symbols corresponding to Sun
/Sunday
h
/hh
: 12-hour symbols corresponding to 01
/01 PM
H
/HH
: 24-hour symbols corresponding to 13
/13
m
/mm
: minute symbols corresponding to 5
/05
s
/ss
: second symbols corresponding to 5
/05
z
/Z
: minute symbols corresponding to Pacific Standard Time
/GMT-8:00
In addition, there are some predefined formats:
medium
: equivalent to yMMMdhms
short
: equivalent to yMdhm
fullDate
: equivalent to yMMMMEEEEd
longDate
: equivalent to yMMMMd
mediumDate
: equivalent to yMMMd
shortDate
: equivalent to yMd
mediumTime
: equivalent to hms
shortTime
: equivalent to hm
An important thing is that the formatting depends on the browser-locale. This pipe uses the Internationalization API. Therefore, it is only reliable in Chrome and Opera.
In addition to that, there are some useful pipes. Let’s look at those.
SlicePipe
creates a new list or string from an input one. It’s named slice
and takes two parameters: start
and end
.
@
Component
({
selector
:
'my-cmp'
,
template
:
`
{{
'abcdef'
|
slice
:2
}},
{{
'abcdef'
|
slice
:2
:
4
}}
`
// -> cdef, cd
})
export
class
MyComponent
{
}
SlicePipe
can accept types of only Array
or string
.
AsyncPipe
is a special pipe. Its named async
, and it can transform an async object to a sync value. The async object is an Observable
or a Promise
. When the async object emits new value, AsyncPipe
updates views with the value.
Let’s see the following example:
@
Component
({
selector
:
'my-cmp'
,
template
:
`
{{
asyncData
|
async
}}
`
})
export
class
MyComponent
{
asyncData
=
new
Promise
(
resolve
=>
{
setTimeout
(()
=>
resolve
(
'Hello'
),
1000
);
});
}
asyncData
is a promise object, which will emit a value after 1000ms. And that view is empty before that time.
Also you can use the pipe with Observable
and a view will be updated at each time when the new value is emmitted.
@
Component
({
selector
:
'my-cmp'
,
template
:
`
{{
asyncData
|
async
}}
`
})
export
class
MyComponent
{
asyncData
=
Observable
.
interval
(
1000
)
.
map
(
i
=>
`
Count
:$
{
i
}
`
);
}
I18nPluralPipe
and the following I18nSelectPipe
are helpful pipes for internationalization. I18nPluralPipe
can map a number input and a string output. For example, the following is a simple counter component:
@
Component
({
selector
:
'my-cmp'
,
template
:
`
<
button
(
click
)
=
"itemCount=itemCount+1"
>
Add
item
<
/button>
{{
itemCount
|
i18nPlural
:amountMapping
}}
`
})
export
class
MyComponent
{
itemCount
=
0
;
amountMapping
=
{
'=0'
:
'No items'
,
'=1'
:
'One item'
,
'other'
:
'# items'
};
}
I18nPluralPipe
takes a mapping object as its parameter to pluralize. If the key is '=0'
, that rule will be used when the input is 0
. A special key, 'other'
, is used as the default rule and you can interpolate the actual value with the '#'
sign. In the above case, the rules look like the following:
input | output |
---|---|
0 |
'No items' |
1 |
'One item' |
2 |
'2 items' |
x |
'x items' |
I18nSelectPipe
is almost the same as I18nPluralPipe
. The difference is that pipe maps a string to a string. See the following example:
@
Component
({
selector
:
'my-cmp'
,
template
:
`
<
select
[(
ngModel
)]
=
"gender"
>
<
option
value
=
""
selected
>
select
gender
<
/option>
<
option
value
=
"male"
>
male
<
/option>
<
option
value
=
"female"
>
female
<
/option>
<
/select>
{{
gender
|
i18nSelect
:inviteMap
}}
`
})
export
class
MyComponent
{
gender
=
''
;
inviteMap
=
{
'male'
:
'Invite her.'
,
'female'
:
'Invite him.'
,
'other'
:
'Invite them.'
}
}
I18nSelectPipe
takes an object for mapping. The mapping rule is similar to the JavaScript switch
statement. You can use this pipe to convert a model-side string to a view-side string.
Angular 2 supports creating custom pipes and you can use this easily. Using custom pipes, you can boost speed for developing your awesome application.
You can write your pipes by using the @Pipe
decorator. For example, let’s make a pipe that powers a number input with a given exponent number. First of all, write a simple class that will be the pipe.
export
class
PowerPipe
{
}
Next, decorate this class with the @Pipe
decorator and define the pipe’s name. In this case, the pipe is named power
.
import
{
Pipe
}
from
'@angular/core'
;
@
Pipe
({
name
:
'power'
})
export
class
PowerPipe
{
}
Last, implement the transform
method. It’s defined in the PipeTransform
interface.
import
{
Pipe
,
PipeTransform
}
from
'@angular/core'
;
@
Pipe
({
name
:
'power'
})
export
class
PowerPipe
implements
PipeTransform
{
transform
(
input
:number
,
exp
:number
)
:
number
{
return
Math
.
pow
(
input
,
exp
);
}
}
The transform
method takes several arguments. The first is always an input value. The other arguments are all pipe’s parameters. Above, the pipe can be used by {{ 2 | power:3 }}
and then it displays 8
.
If you want to take multiple parameters like SlicePipe
, you can add method arguments.
// {{ input | somePipe:param1:param2 }}
transform
(
input
,
param1
,
param2
)
{
}
You can use built-in pipes by default. To use your custom pipe, you have to notify it to your component. There is pipes
property in @Component
decorator’s metadata to register additional pipes.
@
Component
({
selector
:
'my-cmp'
,
template
:
`
{{
2
|
power
:3
}}
`
,
pipes
:
[
PowerPipe
]
})
export
class
MyComponent
{
}