Sub topic 7
Working with arrays and objects: slice, keyvalue and json
This chapter assumes you know basic TypeScript, Angular template interpolation, and how a standalone component lists its dependencies in imports. It covers three built-in pipes for collections and debugging: slice, keyvalue and json.
The slice pipe
SlicePipe takes part of an array or a string. It works like Array.prototype.slice and String.prototype.slice. The first parameter is the start index. The second is the end index, which is excluded. Negative values count from the end.
import { Component } from '@angular/core';
import { SlicePipe } from '@angular/common';
@Component({
selector: 'app-top-items',
standalone: true,
imports: [SlicePipe],
template: `
<ul>
@for (item of items | slice:0:3; track item) {
<li>{{ item }}</li>
}
</ul>
<p>{{ title | slice:0:10 }}</p>
<p>Last two: {{ items | slice:-2 }}</p>
`,
})
export class TopItemsComponent {
items = ['Alpha', 'Beta', 'Gamma', 'Delta', 'Epsilon'];
title = 'Angular pipes are useful';
}The loop shows Alpha, Beta and Gamma. The title becomes Angular pi. slice:-2 returns Delta and Epsilon. The pipe returns a new array and leaves items unchanged. If the input is null or undefined, it returns null.
The keyvalue pipe
A @for loop iterates arrays, not plain objects. KeyValuePipe turns an object or a Map into an array of { key, value } entries that a loop can use.
import { Component } from '@angular/core';
import { KeyValuePipe } from '@angular/common';
@Component({
selector: 'app-stock',
standalone: true,
imports: [KeyValuePipe],
template: `
<table>
@for (entry of stock | keyvalue; track entry.key) {
<tr>
<td>{{ entry.key }}</td>
<td>{{ entry.value }}</td>
</tr>
}
</table>
`,
})
export class StockComponent {
stock = { pears: 4, apples: 12, plums: 7 };
}By default the entries are sorted by key, so the rows appear as apples, pears, plums, not in insertion order. This sorting is a common surprise.
To keep the original order, pass a comparer function that always returns 0. To sort by value, pass your own comparer. A comparer receives two KeyValue entries and returns a number, as in Array.prototype.sort.
import { Component } from '@angular/core';
import { KeyValue, KeyValuePipe } from '@angular/common';
@Component({
selector: 'app-stock-sorted',
standalone: true,
imports: [KeyValuePipe],
template: `
@for (entry of stock | keyvalue:byValueDesc; track entry.key) {
<p>{{ entry.key }}: {{ entry.value }}</p>
}
`,
})
export class StockSortedComponent {
stock = { pears: 4, apples: 12, plums: 7 };
byValueDesc = (a: KeyValue<string, number>, b: KeyValue<string, number>): number =>
b.value - a.value;
}Define the comparer as a property, as above, so the same function reference is used on every check.
The json pipe
JsonPipe calls JSON.stringify on a value with two-space indentation. It is a debugging aid. Place it inside a <pre> element to keep the line breaks.
<pre>{{ user | json }}</pre>For user = { name: 'Ada', roles: ['admin', 'dev'] }, the output is:
{
"name": "Ada",
"roles": [
"admin",
"dev"
]
}Because it uses JSON.stringify, the pipe drops undefined and function values, and it throws an error on circular references. Remove it before shipping, since it exposes raw data to users.
Common errors
| Mistake | Result | Fix | Column |
|---|---|---|---|
| Using `@for` on a plain object without `keyvalue` | Compile or runtime error, because objects are not iterable | Add `\ | keyvalue` |
| Expecting insertion order from `keyvalue` | Rows are sorted by key | Pass a comparer that returns `0` | |
| Forgetting to import the pipe | Template error: pipe not found | Add it to the component's `imports` | |
| Passing a circular object to `json` | Error thrown while rendering | Log a trimmed copy instead |
Exercise
A component has scores = { zoe: 90, adam: 75, mia: 82 }. Write the template loop that lists the entries in the object's original order, not sorted by key.
Show answer
Pass a comparer that returns 0: define keepOrder = () => 0; in the class and write @for (entry of scores | keyvalue:keepOrder; track entry.key) { <p>{{ entry.key }}: {{ entry.value }}</p> }. Without the comparer, the order would be adam, mia, zoe.
Exercise
Which expression shows only the first four characters of code, and what does it return when code is null?
Show answer
{{ code | slice:0:4 }}. For null the pipe returns null, which interpolation renders as an empty string.