The range pipe generates an array of numbers within a specified range, making it ideal for creating dropdown options, pagination controls, or any scenario requiring numeric sequences in templates. When working with Angular templates, you may need to generate an array of numbers for iteration. For example, if you have the number 20 and want to create an array from 1 to 20 to display in a dropdown list, Angular's @for directive cannot directly iterate over a number. While you could generate this array in TypeScript, there are cases where creating the array directly in the template is more convenient.
The range pipe creates an array of numbers (positive and/or negative) progressing from start up to, but not including, end.
A step of -1 is used if a negative start is specified without an end or step.
If end is not specified, it's set to start with start then set to 0.
A range utility function is also available for use in TypeScript, which can be imported from ngx-lift.
Examples
Example 1: Basic Range
Generate arrays with different start and end values:
import {RangePipe} from'ngx-lift';
@Component({
imports: [RangePipe],
template: `
<p>{{ [1, 5] | range }}</p>
<!-- Output: [1,2,3,4] -->
<p>{{ [10, 5] | range }}</p>
<!-- Output: [10,9,8,7,6] (start is bigger than end) -->
`
})
exportclassRangeExampleComponent {}
Generate CPU count options for a dropdown. This is useful when displaying a list of computers with varying maximum CPU counts and allowing users to select a CPU range.