Range

Assume you have the number 20. In Angular HTML, you want to create an array ranging from 1 to 20 and display it in a dropdown list. You might find that Angular's *ngFor loop cannot directly iterate over a number, requiring you to create an array first. While you could generate this array in TypeScript, there might be cases where you prefer to create such an array directly in the HTML. For instance, if you have a list of computers with varying maximum CPU counts, and you wish to allow users to select a range of CPUs in a dropdown list, a custom "range" pipe would be useful for generating the necessary array.

The pipe accepts a tuple containing a start number, an end number, a step value, and a boolean flag indicating whether the array should be in reverse order. The default value for the step is 1. When only one number is passed, the array will be starting from 0 to that number.

Usage

import {RangePipe} from 'ngx-lift';

@Component({
  standalone: true,
  imports: [RangePipe],
  template: `
    <p>{{ [1, 5] | range }}</p>
    <!-- generate an array from 1 to 4: [1,2,3,4] -->

    <p>{{ [10, 5] | range }}</p>
    <!-- generate an array from 10 to 6 since start is bigger than end: [10,9,8,7,6] -->

    <p>{{ [1, 5, 2] | range }}</p>
    <!-- stepper by 2: [1,3] -->

    <p>{{ [1, 5, 1, true] | range }}</p>
    <!-- reverse the array by passing true: [4,3,2,1] -->
  `
})
export class RangePipeComponent { }
<div class="space-x-6">
  <label for="cpu-count">Choose CPU count</label>
  <select id="cpu-count">
    @for (count of [1, 5] | range; track count) {
      <option [value]="count">{{ count }} CPU(s)</option>
    }
  </select>
</div>