Retrieving the length of a Pipe in the parent component using Angular 2

In Angular2, I have created a custom pipe to filter an array based on type ID and year arrays. Here is how it is defined:

@Pipe({name: 'highlightedWorksFilter', pure: false})
export class HighlightedWorksFilterPipe implements PipeTransform {
transform(works: IHighlightedWork[], activityTypeIds: any[], activityYears: any[]){
    if (works && works.length) {
        return works.filter(work => {
            if(activityTypeIds.findIndex(i => i.id === work.activityTypeId && i.checked) === -1) {
                return false;
            }
            if (activityYears.findIndex(i => i.year === work.activityYear && i.checked) === -1) {
                return false;
            }
            return true;
        });
    } else {
        return works;
    }
}
}

It is used in the calling component like this:

<div>FILTERED COUNT / {{highlightedWorks.length}}</div>
<div *ngFor="let work of highlightedWorks | highlightedWorksFilter: myActivityTypeIds:myActivityYears">
 {{work.Title}}
</div>

The filter works perfectly with the checkbox list arrays for type and year. My question is, how can I display the FILTERED COUNT outside of the ngFor loop to show the number of results after the pipes are applied?

Answer №1

It is recommended to implement the filtering logic within the component code instead of using a pipe. This approach offers better flexibility and performance, as explained in detail here: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

By handling the filter directly in the component, you can easily access the filtered list as a property of the component class and perform operations like getting its length.

Below is an illustrative example:

import { Component, OnInit } from '@angular/core';

import { IProduct } from './product';
import { ProductService } from './product.service';

@Component({
    templateUrl: './product-list.component.html'
})
export class ProductListComponent implements OnInit {

    _listFilter: string;
    get listFilter(): string {
        return this._listFilter;
    }
    set listFilter(value: string) {
        this._listFilter = value;
        this.filteredProducts = this.listFilter ? this.performFilter(this.listFilter) : this.products;
    }

    filteredProducts: IProduct[];
    products: IProduct[] = [];

    constructor(private _productService: ProductService) {

    }

    performFilter(filterBy: string): IProduct[] {
        filterBy = filterBy.toLocaleLowerCase();
        return this.products.filter((product: IProduct) =>
              product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
    }

    ngOnInit(): void {
        this._productService.getProducts()
                .subscribe(products => {
                    this.products = products;
                    this.filteredProducts = this.products;
                },
                    error => this.errorMessage = <any>error);
    }
}

Answer №2

Recently ran into an issue with angular 15 and tried out the solution provided.

I concur with DeborahK's suggestion to filter within the component itself.

However, for those interested in filtering directly in the template, you can achieve it using

{{ (highlightedWorks | highlightedWorksFilter: myActivityTypeIds:myActivityYears).length }}

Answer №3

If you need to determine the length of your filtered list in Angular, you can utilize a basic index on *ngFor where the last value corresponds to the index of the last filtered element. By adding 1 to this value, you can easily obtain the length of your filtered list.

<div *ngFor="let work of highlightedWorks | highlightedWorksFilter: myActivityTypeIds:myActivityYears; let i=index" [i]="i">
 {{work.Title}} Index: {{i+1}}
</div>

In order for this functionality to work properly, make sure to input the value into your component:

@Input() i: number;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Javascript Macros for Mastering Excel

My goal is to use Javascript macros to handle excel spreadsheets instead of the standard VBA. I have found a way to run javascript code through VBA, as shown below: 'javascript to execute Dim b As String b = "function meaningOfLife(a,b) {return 42;}" ...

Angular service worker does not start automatically unless an interval is specified

After deploying my SPA to production, I'm looking for a way to automatically reload the page whenever there's an update. Setting an interval to check for updates every X minutes doesn't seem like the most efficient solution. Does anyone have ...

Coloring input fields in Angular Material 2

Changing Angular Material 2 Input Color <md-input-container > <input type="password" md-input placeholder="password"> </md-input-container> I am looking to change the color of the input field when it is clicked. Can anyone provide gu ...

Post-installation of NPM, configuring CA certificates on Windows system

TLDR; Is there a way to seamlessly set NODE_EXTRA_CA_CERTS in a Windows environment for NPM packages' post-install scripts without requiring system changes, configuration file modifications, or admin-level permissions? Details This issue has been f ...

Acquiring and resetting Angular states: A beginner's guide

I'm facing a situation where I need to perform a route jump (essentially a refresh) on the same page, but this jump includes state data. However, even though the state contains valuable information, I am only able to access it through history and cann ...

Error encountered when compiling styles.css in Angular 2

Having trouble compiling my Angular 2 application that was previously successful. Unsure of the issue. Here is the error message I am receiving: View error ...

Sorting arrays with NaN values within objects will not result in a reordering when using the Array

I encountered a situation where I need to reorder items in an array based on the property minLVL of each object within the array. However, I have discovered that this reordering only works if the previous and next items have the required minLVL field. If ...

Sender receives a response from Socket.io

My goal is to have a socket respond only to the sender. Currently, I am working on having the user connect to the server using JavaScript when they visit any webpage. However, I am unsure whether the connection will be reset each time the user reloads th ...

A guide on calculating the number of days between two dates using Angular 12

I am currently utilizing Angular 12 for my project. The calculation of days based on two dates seems to be working perfectly fine in Chrome, but unfortunately, it fails in Firefox. In my TypeScript file: getDaysCount(firstDate: any, secondDate: any) { ...

What is the process for subscribing to setInterval() in an Angular application?

I'm currently working on developing an iOS location tracking application using the Ionic 5 Framework, Angular, and the Cordova Geolocation Plugin. In the past, I was able to track user location changes using the watchPosition() function, which worked ...

Can the submit ID value be utilized in PHP?

name="submit" functions as expected. if(isset($_POST["submit"])) <input type="submit" ID="asdf" name="submit" value="Save" class="ui blue mini button"> I want to change it to use ...

Experiencing delays with Angular 4 CLI's speed when running ng serve and making updates

After running ng serve, I noticed that the load time is at 34946 ms, which seems pretty slow and is impacting our team's performance. Additionally, when we update our code, it takes too long to reload the page. https://i.sstatic.net/lpTrr.png My Ang ...

Previewing an uploaded image before submitting with FileBase64: A step-by-step guide

How can I implement a preview for an uploaded image before submitting the form? I have the upload functionality working but I would like to add a preview feature for the image. Below is the code snippet I am currently using: const [shop, setShop] = us ...

Where to begin with Angular materials?

Here is a snippet of my Angular materials test code: <div class="radioButtondemoBasicUsage" ng-app="MyApp"> <form ng-submit="submit()" ng-controller="AppCtrl"> <p>Selected Value: <span class="radioValue">{{ data.group1 }}< ...

How can state values be transferred between components?

I have come across various answers on different platforms but haven't been able to achieve the desired results. That's why I am reaching out with this question. So, my question is related to 3 files named: App.js, SignUp.js, and Welcome.js. My ...

I am facing an issue where the module pattern functions perfectly on JSBin, but fails to work properly

As a backend developer, I typically only write JavaScript when absolutely necessary, and not always in the best way. However, I have decided to turn over a new leaf and start writing more organized code that follows best practices as much as possible. To ...

Any alterations made to an object in one component result in changes being reflected across all components

I currently have the following item.ts file: item.ts export interface IItem { name: string; isActive?: boolean; } const data: IItem[] = [ { name: 'item1', isActive: true }, { name: 'item2', isActive: true } ...

Having trouble limiting the number of special characters in AngularJS

I am having trouble restricting special characters and spaces in the input text field. I tried using the following code snippet: ng-pattern="/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/" to prevent special characters, but it doesn't seem to be workin ...

Modifying the value of a property in one model will also result in the modification of the same

As a beginner with Vue, I am looking to allow users to add specific social media links to the page and customize properties like text. There are two objects in my data - models and defaults. The defaults object contains selectable options for social media ...

Get only the text content from a hyperlink using Tinymce-4

Within tinymce.activeEditor, I currently have this line of innerHTML code (part of a ul-list): <li><a href="#">Important words</a></li> When I place the caret within the sentence "Important words," and click a button with the foll ...