Reputation: 154
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.
Upvotes: 4
Views: 3065
Reputation: 305
A better solution will be to change the way you are adding and removing elements from listOfIdToExport
array. You can change the reference to the array so that angular change detection works instead of making the pipe impure.
Upvotes: 0
Reputation: 50633
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.
Upvotes: 6