Angular 4 Filtering Pipe: Simplify Data Filtering in Angular

Attempting to replicate AngularJS's OrderBy feature.

Working with an array like this, I am aiming to filter the cars by their car category.

[
  {
    "car_category": 3,
    "name": "Fusion",
    "year": "2010"
  },
  {
    "car_category": 2,
    "name": "Mustang",
    "year": "2010"
  },
  {
    "car_category": 3,
    "name": "Fiesta",
    "year": "2010"
  },
]

This is the current state of my code:

car.component.html

<div *ngIf="products">
  <ul *ngFor="let product of products | filterBy: car_category">
    <li>{{car.name}}</li>
  </ul>
</div>

car.component.ts

import { Component, OnInit } from '@angular/core';
import { CarService } from '../car.service';
import { ICars } from '../ICars';
import { FilterByPipe } from '../filter-by.pipe';

@Component({
  selector: 'app-home-page',
  templateUrl: './car.component.html',
  styleUrls: ['./car.component.css']
})
export class CarComponent implements OnInit {
  cars: Array<ICars>;
  errorMessage: string;
  filteredCars: any;
  car_category= 3;

  constructor(private _carService: CarService) { }
  ngOnInit() {
     this._carService.getCars()
      .subscribe(
        cars => this.cars = cars,
        error => this.errorMessage = error
      );
  }

}

filet-by.pipe.ts

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

@Pipe({
  name: 'filterBy'
})
export class FilterByPipe implements PipeTransform {

  transform(value, args) {
    if (!args[0]) {
      return value;
    } else if (value) {
      return value.filter(item => {
        // tslint:disable-next-line:prefer-const
        for (let key in item) {
          if ((typeof item[key] === 'string' || item[key] instanceof String) &&
            (item[key].indexOf(args[0]) !== -1)) {
        return true;
      }
    }
  });
}
  }

}

How should I improve my pipe?

UPDATE Here is a snippet of my current pipe. Note that the car is represented as a number and the year as a string.

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

@Pipe({
  name: 'filterBy'
})
export class FilterByPipe implements PipeTransform {

  transform(value, args) {
    if (!args[0]) {
      return value;
    } else if (value) {
      return value.filter(item => {
        // tslint:disable-next-line:prefer-const
        for (let key in item) {
          if ((typeof item[key] === 'number' || item[key] instanceof Number) &&
            (item[key].indexOf(args[0]) !== -1)) {
        return true;
      }
    }
  });
}
  }

}

Answer №1

Creating custom generic pipes can be quite complex. If you take a peek at the Angular 1 source code, you'll see what I'm talking about.

That's why my recommendation is to utilize a library like ng-pipes. I haven't tried the Angular 2 version personally, but it was really helpful for Angular 1.

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

How to prevent redundant object declarations when passing parameters in TypeScript?

Motivation for Using Object Parameters One of the motivations behind using objects as function parameters is to allow the caller to clearly define arguments with specified field names, which can make code reviews easier. Challenge When Using Implements an ...

Guide on how to specify the return type for useMutation in the 'react-query' library

Here is the code snippet provided: const setFriendCode = (data: Params) => api({ data }) const [mutateSetFriendCode, state] = useMutation<Response, Params>( setFriendCode ) An issue arises with the type of parameters in the code. The compiler ...

What is the best way to extract accurate information from an observable?

I'm having trouble retrieving the correct data from an observable in my project. Here is the code for my API call: getLastxScans(amount: number): Observable<Scan[]> { return this.http.get<Scan[]>(`${this.ROOT_URL}/Scan/amount/${amo ...

The width of table cells expands even when using the box-sizing property set to border-box

Whenever I click the View button, I want to apply padding to the cells in my table. However, this action also increases the width of the cell. Despite researching various solutions like those found in this question, this one, and this post, I still encount ...

Unable to find custom components when using react-router

My goal is to improve the organization of my Routes in React and separate concerns. I am currently utilizing react-router-dom version 5. Within my Application Routes component, I have structured it with 3 children components: AuthenticatedRoutes PublicRo ...

The declaration file for module 'react/jsx-runtime' could not be located

While using material-ui in a react project with a typescript template, everything is functioning well. However, I have encountered an issue where multiple lines of code are showing red lines as the code renders. The error message being displayed is: Coul ...

Struggling to implement mock JSON data, unable to dynamically update on HTML page

Although the data is being displayed, I am facing issues with getting the images to appear correctly based on the syntax and code. https://i.sstatic.net/ip4kp.png <h2>Amazing Places on Earth</h2> <div class="card"> <div class=" ...

Troubleshooting the error message "TypeError: Cannot read property 'name' of undefined" when working with data binding in Angular 4

I am brand new to Angular and I have been working on creating a custom Component. Specifically, I am trying to display a list of Courses (objects) which consist of two properties: id and name. So far, this logic is functioning properly. However, when attem ...

An effective method for targeting a specific button within a CSS file

I have multiple button tags in my code, but I need to style a specific one using CSS. How can I target this particular button and apply styles only to it while leaving the others unchanged? Do I need to assign the button to a variable and reference that va ...

Node.js and mongoose provide a powerful tool for filtering documents dynamically by leveraging a variable that is dependent on another document. Want to learn

I've hit a bit of a roadblock here... I'm trying to add a new property to a document that will change based on the values in that document as well as another document. Let me provide an example to clarify. First, I have a Candidate Schema: const ...

Struggling to position a div below another div within a flex box layout

When trying to make the Information & advice header appear above the other div elements, I encountered an issue with flexbox. Despite setting the container div to have a flex direction of column, the header div continued to align to the left of the oth ...

Prevent Ionic 2 hardware back button from triggering default action

Is there a way to prevent the default navigation when tapping the hardware back button? I attempted using registerBackButtonAction, but it ends up overriding the behavior of the back button on every page, which is not desired. I also tried this method: d ...

Creating a Class in REACT

Hello fellow coding enthusiasts, I am facing a minor issue. I am relatively new to REACT and Typescript, which is why I need some assistance with the following code implementation. I require the code to be transformed into a class for reusability purposes ...

Resolve the conflict with the upstream dependency in Angular

I understand that the solution to this issue can be found on SOF, but utilizing --legacy-peer-deps or --force is not an option for me on my production server. I am eager to comprehend the root cause of this error and find a proper resolution. Upon install ...

Enhancing search capabilities in Angular 8.1.2 by filtering nested objects

I am in need of a filter logic similar to the one used in the example posted on this older post, but tailored for a more recent version of Angular. The filtering example provided in the older post seems to fit my requirements perfectly, especially with ne ...

Issue with TailwindCSS @apply not compiling in Angular v12 component styles

I am a computer science student working on a project for my studies. I am currently developing a component library for the Angular framework using Angular V12. To style the components, I have decided to use Tailwindcss as it simplifies some aspects like me ...

Blend the power of Node's CommonJS with the versatility of Typescript's ES modules

I currently have a Node.js v10 legacy application that was built using CommonJS modules (require). The entire codebase is written in JavaScript. However, I am considering upgrading the app and refactoring a specific part of it to use TypeScript modules ( ...

What methods can be implemented to ensure ComponentOverride's universality?

These type definitions for markdown-to-jsx don't seem to be generic enough, causing issues like the one mentioned below. For more details, refer to Why is type SFC<AnchorProps> not assignable to type SFC<{}>? /Users/sunknudsen/Sites/sunk ...

What are the best practices for effectively using RxJs subscriptions?

I'm looking for some advice on how to handle Angular and RxJs mechanics. I have server-side pagination set up on my backend and three components on the frontend: a data list, filters, and a pagination component. How can I subscribe to two streams (pag ...

Issue: Using the command 'typings search' successfully locates a package, however, when attempting to install it using 'typings install', the process fails

I am currently attempting to install the Google Auth2 typings using 'typings': > typings search gapi.auth2 This command returns: NAME SOURCE HOMEPAGE DESCRIPTION VERSIONS UPDATED gapi.auth2 d ...