Angular Pipes-2
1. The Slice Pipe (slice)
Description:
The slice pipe is used to extract a subset of a collection. It works on both Strings and Arrays. It creates a new instance containing only the elements from the specified start index up to (but not including) the end index.
Possible Values & Parameters:
start: The zero-based index where the slice begins (inclusive). If negative, it indicates an offset from the end of the sequence.end: (Optional) The zero-based index where the slice ends (exclusive). If omitted, it slices until the end of the sequence.
Code Example:
2. The JSON Pipe (json)
Description:
The json pipe converts a JavaScript object or array into a formatted JSON string. Its primary purpose is debugging. Instead of seeing [object Object] on your screen, you can see the actual properties and values inside your data structure.
Possible Values:
- It takes no parameters. It simply serializes the input using
JSON.stringify.
Code Example:
The KeyValue Pipe (keyvalue)
Description
By default, the *ngFor directive in Angular can only iterate over Arrays. If you try to loop through a standard JavaScript Object or a Map, Angular will throw an error. The keyvalue pipe transforms these structures into an array of objects, where each entry contains a key and a value property.
TypeScript Side (.ts)
In your component, you define the data as a standard Object or a Map. We also often define a comparator function if we want to change the default alphabetical sorting.
Template Side (.html)
In the template, you apply the pipe to the object or map. You access the data using .key and .value.
Summary Table: Collection Management
| Pipe | Target Type | Main Use Case | Behavior |
slice | Array, String | Pagination / Truncation | Returns a subset of data. |
json | Any Object | Debugging | Converts data to a readable string. |
keyvalue | Object, Map | Iteration | Makes objects compatible with *ngFor. |