Sub topic 7
Working with arrays and objects: slice, keyvalue and json
This chapter covers three built-in pipes that work on collections: slice, keyvalue and json. It assumes you know basic TypeScript syntax, Angular components with template interpolation, and how a standalone component lists its dependencies in imports. You should also know the pipe operator and how to pass parameters after a colon, which earlier chapters cover.
All three pipes are exported from @angular/common. SlicePipe, KeyValuePipe and JsonPipe are standalone, so you add each one to the imports array of any standalone component that uses it in its template. The examples below do that.
The slice pipe
slice returns a portion of an array or a string. It behaves like Array.prototype.slice and String.prototype.slice: the first parameter is the start index, and the optional second parameter is the end index, which is excluded.
<p>{{ 'Angular' | slice:0:3 }}</p>
<!-- Ang -->
<ul>
@for (item of items | slice:0:3; track item) {
<li>{{ item }}</li>
}
</ul>Behavior worth knowing:
- Negative indexes count from the end.
slice:-2returns the last two elements. - If you omit the end index, the slice runs to the end of the collection.
- The pipe returns a new array. The original array is not changed.
nullandundefinedinput returnnull, so the pipe is safe with data that has not loaded yet.- The input must be an array, a string,
nullorundefined. Anything else, such as a plain object, throws a runtime error.
A common use is to show a preview of a long list with a "show more" button.
import { Component } from '@angular/core';
import { SlicePipe } from '@angular/common';
@Component({
selector: 'app-preview-list',
standalone: true,
imports: [SlicePipe],
template: `
<ul>
@for (item of items | slice:0:visibleCount; track item) {
<li>{{ item }}</li>
}
</ul>
@if (visibleCount < items.length) {
<button type="button" (click)="visibleCount = visibleCount + 3">Show more</button>
}
`,
})
export class PreviewListComponent {
items = ['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Golf'];
visibleCount = 3;
}The keyvalue pipe
@for iterates arrays and other iterables, not plain objects. The keyvalue pipe converts an object or a Map into an array of { key, value } entries, which @for can then iterate.
import { Component } from '@angular/core';
import { KeyValuePipe } from '@angular/common';
@Component({
selector: 'app-scores',
standalone: true,
imports: [KeyValuePipe],
template: `
<ul>
@for (entry of scores | keyvalue; track entry.key) {
<li>{{ entry.key }}: {{ entry.value }}</li>
}
</ul>
`,
})
export class ScoresComponent {
scores = { mathematics: 91, physics: 84, art: 97 };
}This renders art: 97, mathematics: 91 and physics: 84, in that order. Each entry has two properties, key and value.
Default ordering
By default the pipe sorts entries by key in ascending order. This surprises many learners, because the sorted order differs from the insertion order of the object. Here the source object lists mathematics first, but the output starts with art.
The sort rules are:
- String keys are compared as strings.
- Number keys are compared as numbers.
- Entries with the same key type follow that comparison. Mixed types are handled by the built-in default comparer, so avoid mixing them.
A custom comparer
The pipe accepts one optional parameter: a compare function with the signature (a, b) => number. Both a and b are { key, value } entries. Return a negative number to place a first, a positive number to place b first, and zero to keep them equal.
Sorting by value, highest first:
import { Component } from '@angular/core';
import { KeyValuePipe, KeyValue } from '@angular/common';
@Component({
selector: 'app-ranking',
standalone: true,
imports: [KeyValuePipe],
template: `
<ol>
@for (entry of scores | keyvalue:byScoreDescending; track entry.key) {
<li>{{ entry.key }} ({{ entry.value }})</li>
}
</ol>
`,
})
export class RankingComponent {
scores: Record<string, number> = { mathematics: 91, physics: 84, art: 97 };
byScoreDescending = (a: KeyValue<string, number>, b: KeyValue<string, number>): number =>
b.value - a.value;
}To keep the original insertion order, return 0 from the comparer for every pair:
keepOrder = (): number => 0;Then use scores | keyvalue:keepOrder in the template. The sort is stable, so equal entries stay in their original positions.
Define the comparer as a class property (an arrow function, as above) or a method that does not depend on a changing reference. If you write the function inline in the template, Angular does not allow it. If you use a regular method that relies on this, the pipe calls it without the component as this, and this will be wrong. An arrow-function property avoids that problem.
Maps and typing
keyvalue also accepts a Map, and the keys keep their type. With a Map<number, string>, entry.key is a number.
@for (entry of countryNames | keyvalue; track entry.key) {
<p>{{ entry.key }} = {{ entry.value }}</p>
}Like slice, the pipe returns null when the input is null or undefined, and @for over null renders nothing. The pipe is also pure in a specific way: it detects changes to the keys and values of the input object, not only its reference. If you add a property to the same object, the pipe recomputes on the next change detection. This differs from slice, which only reacts to a new reference.
The json pipe
json converts any value to a string with JSON.stringify(value, null, 2), so the output is indented by two spaces. It is a debugging aid. Use it to see what an object contains while you build a template.
<pre>{{ user | json }}</pre>For user = { id: 7, name: 'Ada', roles: ['admin', 'editor'] }, the output is:
{
"id": 7,
"name": "Ada",
"roles": [
"admin",
"editor"
]
}Wrap the output in a <pre> element. HTML collapses whitespace in other elements, so without <pre> the indentation and line breaks disappear.
Points to remember:
- The pipe is impure, which means it runs on every change detection cycle. Angular
JsonPipeis declared withpure: false, so it always shows the current state of the object, including in-place mutations. - Because it runs often, it can slow a large page. Remove it when you finish debugging.
- It inherits the behavior of
JSON.stringify. Functions andundefinedvalues inside objects are omitted,Dateobjects become ISO strings, and a circular reference throws aTypeError. - It is not a formatter for end users. Show users readable fields, not raw JSON.
You can combine it with the async pipe to inspect an Observable:
<pre>{{ user$ | async | json }}</pre>While the Observable has not emitted, async returns null, so the template shows null.
Choosing between the three
| Need | Pipe | Notes |
|---|---|---|
| Show the first few items of a list, or part of a string | `slice` | Pure. Needs a new array reference to update. |
| Loop over the properties of an object or the entries of a Map | `keyvalue` | Sorted by key unless you pass a comparer. |
| Inspect a value while debugging | `json` | Impure. Use `<pre>`. Remove before release. |
Common errors
- Using
sliceon an object.{{ obj | slice:0:2 }}throws anInvalidPipeArgumenterror. Usekeyvaluefirst if you need entries, then slice the resulting array. - Expecting insertion order from
keyvalue. The default output is sorted by key. Pass a comparer that returns0to keep the original order. - Mutating an array and expecting
sliceto update. Create a new array reference when the data changes. - Looping over an object with
@fordirectly. Plain objects are not iterable, so useobj | keyvalue. - Leaving
jsonin production templates. It runs on every change detection cycle and exposes raw data.
Chaining works with these pipes as it does with any other. To show the two highest scores, pipe the entries through slice:
@for (entry of scores | keyvalue:byScoreDescending | slice:0:2; track entry.key) {
<li>{{ entry.key }}: {{ entry.value }}</li>
}Pipes run from left to right, so keyvalue produces the sorted array and slice keeps its first two entries.
Exercise
A component has settings = { theme: 'dark', language: 'en', fontSize: 14 }. You write @for (entry of settings | keyvalue; track entry.key) and print entry.key. In which order do the keys appear, and how do you make them appear in the order theme, language, fontSize?
Show answer
The keys appear sorted ascending by key: fontSize, language, theme. To keep the original insertion order, pass a comparer that always returns 0, for example keepOrder = (): number => 0; in the component and settings | keyvalue:keepOrder in the template.
Exercise
You show {{ items | slice:0:3 }} as a list. A button handler runs this.items.push('New'), but the list does not change even though items now has a new element at the end. Why, and what is a fix? Would a fix be needed if the first three elements stay the same?
Show answer
slice is a pure pipe, so it reruns only when the array reference or a parameter changes. push mutates the same array, so the pipe does not rerun. Fix it by assigning a new array, such as this.items = [...this.items, 'New']. If the first three elements stay the same, the visible output would be identical anyway, so no visible change is expected. The new reference matters when the change affects the first three items, for example when inserting at the start.