Upgrade Angular 8 by substituting interconnected filter and order pipelines with custom functions

According to the Angular documentation

Filtering and sorting operations can be resource-intensive. When Angular invokes these pipe methods frequently, it can lead to a degraded user experience, especially with even moderately-sized lists. Misuse of filter and orderBy in AngularJS apps has resulted in complaints about the performance of Angular itself.

I initially implemented filter, order, and search pipes in my application and didn't face any performance issues. However, lately, they have started causing some problems.

In my application, I have something similar to this setup:

component.html

<ul>
  <li *ngFor="let user of users | filter: filters | order: order | search: searchTerm"></li>
</ul>

component.ts

users = [
  {
    firstName: "Steve", 
    lastName: "Smith", 
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff8b9a8c8bbf8b9a8c8bd19c9092">[email protected]</a>", 
    id: 102, 
    tags: [
      'newUser',
      'important',
      'funny'
    ]
  },
  // More user data...
];

While the current implementation is functional, I understand that it may not be performing optimally.

The respective filter.pipe.ts and order.pipe.ts files contain logic for filtering and ordering users based on various criteria, which is currently being applied as chained pipes.

My plan is to refactor these pipes into functions, but I am unsure about the best way to chain them effectively while maintaining the same functionality.

One approach I'm considering involves chaining the functions like this:

private USERS: Users = [ ... ];
public users: Users;
this.users = this.search(this.order(this.filter(this.USERS, filters), order), searchTerm); 

Is this method the most efficient solution?

Answer №1

Whenever a parameter is modified, the entire sequence of pipes needs to be executed. To prevent this issue, it's best to separate your pipes.

<ng-container *ngIf="users | filter: filters as filtered">
   <ng-container *ngIf="filtered | order: order as ordered">
      <ng-container *ngIf="ordered | search: searchTerm as searched">
         <li *ngFor="let user of searched"></li>
      </ng-container>
   </ng-container>
 </ng-container>

Only the relevant <ng-container> will be refreshed when either the order or searchTerm parameters change. The key requirement here is that all conditions must return a truthy value for the *ngIf="xxx as yyy" statement to function correctly. Your example should work fine in this case.

Answer №2

In my quest for a solution, I delved into some research and formulated the following approach

I eliminated the pipes from the equation and devised a utility class that links all the functions together to produce the desired result

sort-users.ts

export class SortUsers {
   private _users: Users[];

   constructor(@Optional() users: Users[]) {
     this._users = users;
   }

   private search() {
     // ...
     return this;
   }

   private filter() {
     // ...
     return this;
   }

   private order() {
     // ...
     return this
   }

   public sort(users, searchTerm, filters, order) {
      const sort = new SortUsers(users);
      return sort
        .search(searchTerm)
        .filter(filters)
        .order(order)
   }
}

Subsequently, within my component

private USERS: Users[];
users: Users[]

// ...

constructor(
  private _sort: SortUsers
) {}

// ...

sortUsers() {
   // ...
   this.users = this._sort(this.USERS, this.searchTerm, this.filters, this.order);
}

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

Angular failing to render data in user interface

Exploring the concept of CRUD Operations, I am attempting to implement basic CRUD operations using Angular for the front end and Web API for the back end. The API is quite straightforward, returning a simple JSON structure as shown below: [ { "stud ...

Printing problems with Angular POS software

Looking for a way to bypass print preview in Angular 6. I came across this interesting solution: Angular 2 Raw Printing Service Currently utilizing this link for printing in Angular POS. Are there any other options available? .ts code printInvoice() ...

Tips for utilizing playFromPositionAsync method with expo-av Video in React Native

While working with the Video Expo component, I came across a prop called playFromPositionAsync. In the Video.d.ts file, it is defined like this: export default class Video extends React.Component<VideoProps, VideoState> implements Playback { ... ...

React textarea trigger function on blur event

https://codesandbox.io/s/react-textarea-callback-on-blur-yoh8n?file=/src/App.tsx When working with a textarea in React, I have two main objectives: To remove focus and reset certain states when the user presses "Escape" To trigger a callback function (sa ...

Display a child element depending on a certain condition

Looking to implement a switch higher-order component (HOC) for conditional rendering that mimics a switch statement in ReactTS. <Switch> <Case condition={cond1}> Hello </Case> <Case condition={cond2}> Wor ...

Guide on incorporating jQuery into a jQuery plugin within an Angular 2+ application using Webpack or Angular CLI

I'm running into an issue importing a jQuery plugin into a single Angular component. It works fine in most browsers, but IE 11 is giving me this error: SCRIPT1002: Syntax error main.bundle.js (1376,1) When I investigate the error, it points me to th ...

Creating dynamic HTML templates in Webstorm using template strings with Angular 2

As mentioned in the release notes for WebStorm 2016.1, there is an image displayed. Check this out here However, when I try to replicate it, mine ends up looking like this Do I need to manually input the tabs to achieve this result? Shouldn't it au ...

Generating divs dynamically with inline styling and utilizing ngFor, while incorporating a conditional check with ngIf in Angular

Currently, I have an Angular component where I am dynamically generating div elements using the ngFor directive. However, I also need to validate a condition before creating each div, and I'm facing challenges when trying to use both ngFor and ngIf in ...

You are unable to call upon an object that may be of type 'undefined' in typescript

Among all the other inquiries on this topic, my issue lies with the typescript compiler seeming perplexed due to the following code snippet: if(typeof this[method] === "function"){ await this[method](req,res,next) } The error message I am en ...

The error message "Property '$store' is not defined on type 'ComponentPublicInstance' when using Vuex 4 with TypeScript" indicates that the property '$store' is not recognized

I'm currently working on a project that involves using TypeScript and Vue with Vuex. I've encountered an error in VSCode that says: Property '$store' does not exist on type 'ComponentPublicInstance<{}, {}, {}, { errors(): any; } ...

TS7030: In Angular13, ensure that all code paths within the guard and canActivate methods return a value

Having trouble using guards for an unlogged user and constantly facing errors. Error: TS7030 - Not all code paths return a value. Below is my auth.guard.ts file: import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from &a ...

Is there a solution for the error message "Operator '+' cannot be used with types 'string | number' and 'string' | number'"?

Here's the scenario: I'm encountering an issue where I am invoking a function within another function. This inner function has the capability to return either a string or a number, and my goal is to combine that with another value. However, I kee ...

What causes the typescript error in my code: The argument being passed is either a string, an array of FilterData, an array of numbers, or an array of Moments, which is not compatible with a parameter of type 'string'?

When writing my code, I have the need to utilize various types for different scenarios. Depending on the situation, the type may be a string, number[], FilterData[] (a custom type), or Moment[]. To address this requirement, I defined the type as: export ty ...

Communication between Angular components

My question is exactly as the title suggests. Let me explain what I need to do. Currently, I have a component widget. Whenever I click on this widget, a modal pops up with several items inside. Each item corresponds to a different section within the main ...

Creating a personalized attribute directive within Angular2

I've been attempting to apply a custom attribute directive to an input element, but I'm struggling to achieve it. Here is my directive code: @Directive({ selector: '[disable-paste]' }) export class DisablePaste { constructor(p ...

Using regular expressions, replace all instances of " " with ' ' based on certain conditions

I am looking to replace quotes "" with single quotes '' within a string. string = `bike "car" bus "'airplane'" "bike" "'train'"` If a word is inside double quotes, it shoul ...

Is this Firebase regulation accurate and suitable for PUT and GET requests in an Angular and Firebase environment?

Creating a system where users can only see their own posts and no one else can access them is my main goal. Authentication along with posting functionality is already in place and working, but I want to implement this without using Firebase restrictions. ...

Dealing with Cross-Origin Resource Sharing (CORS) issue in an Angular 6 and .Net Core

A project was recently completed involving the development of a .Net Core MVC (angular) app and a .net core Api app CORS has been enabled in both the Web app and API .Net Core services.AddCors(options => { options.AddPolicy("Cor ...

Button activated by specified row index in Angular test

I've been working on testing the enabling or disabling of a button based on the selected rowIndex in Angular 11. However, I'm facing an issue where the test expects component.deleteRoleButtonDisabled to be false but it always evaluates to true. D ...

Angular's '@angular/core/core' module does not have the exported member 'ɵɵFactoryDeclaration'

My Angular application was successfully compiled after running npm install. However, upon executing npm start, I encountered the following error: ERROR in node_modules/ng-apexcharts/lib/chart/chart.component.d.ts:57:21 - error TS2694: Namespace '&quo ...