Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 845
Mistu Avatar asked Sep 05 '25 05:09

Mistu


1 Answers

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.

like image 145
Stefan Svrkota Avatar answered Sep 07 '25 19:09

Stefan Svrkota