Pipes overview - part II

Pipes overview - part II

The last article presented most of the Angular built-in pipes provided with CommonModule. In this part the remaining ones will be covered.

Objects and collections

SlicePipe

SlicePipe is a wrapper for the Array.prototype.slice() method which was described in the Slice it or splice it? article.

collection = [0, 1, 2, 3, 4, 5];
str = '012345'
<span *ngFor="let i of collection | slice:-2">{{i}} </span>
<!-- output: 4 5 -->

<span *ngFor="let i of collection | slice:2:-1">{{i}} </span>
<!-- output: 2 3 4 -->

<p>{{str | slice:-2}}</p>
<!-- output: 45 -->

<p>{{str | slice:2:-1}}</p>
<!-- output: 234 -->

KeyValuePipe

KeyValuePipe allows to iterate through objects (or map) and retrieve key-value pairs.

object = {id: 123, name: 'John'};
map = new Map([[1, 'a'], [2, 'b'], [3, 'c']]);

<span *ngFor="let item of object | keyvalue">
  {{item.key}}: {{item.value | json}}
</span>
<!-- output: id: 123, name: John -->

<span *ngFor="let item of map | keyvalue">
  {{item.key}}: {{item.value}},
</span>
<!-- output: 1: a, 2: b, 3: c-->

JsonPipe

JsonPipe converts objects to readable JSON string representation. Looking at the implementation, it turns out that it is a wrapper for the JSON.stringify() method.

object = {id: 422, name: 'name', obj: {arr: [0,1,2,3]}};
<p>{{object}}</p>
<!-- output: [object Object] -->
<p>{{object | json}}</p>
<!-- output: { "id": 422, "name": "name", "obj": { "arr": [ 0, 1, 2, 3 ] } } -->

Internationalization

I18nPluralPipe

The i18nPluralPipe helps handle the complexity of plural forms in different languages. It's possible to show the correct pluralized string by providing the appropriate mapping.

  elements = [0, 2, 1];
  elementsMapping = {
    '=0': 'None',
    '=1': 'One element',
    'other': '# elements'
  };
  <span *ngFor="let element of elements">
    {{element | i18nPlural: elementsMapping}}, 
  </span>
  <!-- Output: None, 2 elements, One element -->  

I18nSelectPipe

The last of a set of Angular built-in pipes is also used for internationalization. It also uses provided mapping to display localized string. The difference between I18nPluralPipe and I18nSelectPipe is in the type of input data.

  language = 'en';
  <p>{{ language | i18nselect: { 'en': 'english', 'fr': 'français', 'other': 'not supported' } }}</p>
  <!-- output: english -->  

Conclusion

That's it. All of Angular's built-in pipes have been presented. If none of these meet the needs, there is always the option to write custom pipe (docs).