Search code examples
angulartypescriptangular2-pipe

Pipes Angular 2 dynamic Array Length


Is it posible to dynamically show length of array by using pipe? Here's my code:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'lengthOfArray'
})
export class LengthOfArrayPipe implements PipeTransform {

  transform(value: any): number {
    return value.length;
  }

}

I use it like this:

Component

listOfIdToExport: any[] = [];

Template

Element numer: {{ listOfIdToExport | lengthOfArray }}

I have a function which adds or removes elements from this array and problem is that pipe doesn't update array length when change occurs.


Solution

  • Value isn't updated when you add or remove item from an array because your pipe is pure. From Angular docs:

    Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).

    So, you don't change object reference, you only update your array, therefore, solution is to make your pipe impure which will cause it to update value on every change detection cycle:

    @Pipe({
      name: 'lengthOfArray',
      pure: false
    })
    
    export class LengthOfArrayPipe implements PipeTransform {
    
        transform(value: any): number {
            return value.length;
        }
    
    }
    

    You can read more about pipes here.