Instructions for filtering content by manually entering numbers and utilizing Angular 2

Having trouble filtering table contents with multiple fields? Let's take a look at the code:

https://i.sstatic.net/jfLbz.png HTML: Here is the code snippet for filtering data:

<ng-select [options]="name" [(ngModel)]="filter.name"></ng-select>
      <ng-select [options]="email" [(ngModel)]="filter.email"></ng-select>
      <input type="number" onKeyPress="if(this.value.length==10) return false;" class="form-textbox input-text" [(ngModel)]="filter.phone_number">
      <ng-select [options]="pinAddress" [(ngModel)]="filter.address"></ng-select>

Using a pipe to filter the table:

<tbody>
          <tr *ngFor="let pin of pins | pinfilter:filter">
            <td>{{pin.name}}</td>
            <td>{{pin.description}}</td>
            <td>{{pin.address}}</td>
            <td>{{pin.website}}</td>
            <td>{{pin.phone_number}}</td>
            <td>{{pin.email}}</td>
            <td>{{pin.comments}}</td>
          </tr>
        </tbody>

TS:

filter.pipe.ts:
/* Tutorial filter to write filter functions for Tutorial*/
import { Pipe, PipeTransform } from '@angular/core';

export class NewPin { 
  public _id:number;
  public user_id:number;
  public name:string;  
  public address:string;
  public phone_number:string;
  public email:string;
  public comments:boolean;
}

@Pipe({
  name: 'pinfilter',
  pure: false
})

export class PinPipe implements PipeTransform { 
  transform(items: NewPin[], filter: NewPin): NewPin[] { 
    if (!items || (!filter.name && !filter.address)) { 
      return items; 
    } 
      return items.filter((item: NewPin) => this.applyFilter(item, filter)); 
  } 

  applyFilter(user: NewPin, filter: NewPin): boolean {
    console.log(filter);
    if (filter.name && filter.address) { 
      if (filter.name == user.name && filter.address == user.address) { 
        return true 
      } else { 
        return false 
      } 
    } else if (filter.name) { 
        if (filter.name == user.name) { 
          return true 
    } else { 
        return false 
      }  
    } else if (filter.address) { 
      if (filter.address == user.address) { 
        return true 
      } else { 
        return false 
      } 
    } else { 
      return true 
    } 
  } 
}

component.ts:

public filter: NewPin = new NewPin();

Answer №1

In order to improve your applyFilter function, ensure that it compares all filter properties with the data being filtered.

Consider simplifying the structure like this:

applyFilter(user: NewPin, filter: NewPin): boolean {
    console.log(filter);
    // Check all filters
    if (filter.name && filter.name != user.name) { 
        return false; 
    } 
    if (filter.address && filter.address != user.address) { 
        return false 
    }  
    if (filter.email && filter.email != user.email) { 
        return false; 
    }  
    if (filter.phone_number && filter.phone_number != user.phone_number) { 
        return false;
    }  
    // If the user passes all filters, show it
    return true; 
} 

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

Using React and Material UI to create a table filtering system with checkboxes

I'm currently developing a filtering feature using checkboxes for a data display in a project utilizing React and Material-UI. Is there a custom solution available within Material-UI? If not, what steps should I take to achieve this? As I am rel ...

Encountered an error: Invalid usage of hooks. Hooks are intended to be called only within the body of a functional component. - issue with useEffect() function

Encountering an error while attempting to call a function imported within the useEffect() hook in Dashboard.jsx. The goal is to fetch data from the database upon page load, ensuring that users can send the correct credentials to the API with a button click ...

Unit Testing Node.js/NestJS ExceptionFilter Catch Method Using Jest

This code snippet features my custom BadRequestExceptionFilter implemented in Typescript for Nodejs/Nestjs. @Catch(BadRequestException) export class BadRequestExceptionFilter implements ExceptionFilter { constructor(private logger: AppLoggerService) {} ...

What could be causing the JavaScript on my website to not function properly?

I've encountered an issue with the script on my website. Despite double-checking everything and following a tutorial closely, it still doesn't seem to work. Any suggestions or ideas? Here are the links to my GitHub repository and a preview of th ...

What is the best method for eliminating the .vue extension in TypeScript imports within Vue.JS?

I recently created a project using vue-cli3 and decided to incorporate TypeScript for added type safety. Here is a snippet from my src/app.vue file: <template> <div id="app"> <hello-world msg="test"/> </div> </template& ...

Is it possible to refrain from using the object variable name in an ng-repeat loop?

When utilizing an ng-repeat directive to loop through an array, the syntax requires ng-repeat="friend in friends". Inside the template, you can then use the interpolation operator like this {{friend.name}}. Is there a way to directly assign properties to ...

Combining routes in Express and Angular can be achieved by leveraging the power

How can I successfully integrate Jade AngularJS with ExpressJS? I have an app.js file for Express to run the server using Grunt. This app.js file renders home.jade which leads me to the home page. On the homepage, I have implemented AngularJS. I also creat ...

Getting exported members through Typescript Compiler API can be achieved by following these steps:

I am currently working on a project hosted at https://github.com/GooGee/Code-Builder This particular file is being loaded by the Typescript Compiler API: import * as fs from 'fs' Below is a snippet of my code: function getExportList(node: t ...

Using Selenium: Checking for existing dropdown values and incrementing if necessary

I am currently working on automating an application using Selenium Webdriver with Java. The web application I am testing has an Add button that, when clicked, triggers the activation of a dropdown menu. Subsequent clicks on the Add button reveal additional ...

Conceal the bootstrap tooltip instead of completely getting rid of it

Can we hide bootstrap tool-tips without completely removing them? I am utilizing server-side data in the tool-tips and I want to avoid reloading data every time a tool-tip is shown. $('.selector').popover({ animation: true, trigger: &apos ...

What could be the reason behind tsx excluding attribute names with "-" in them from being checked?

Why doesn't TypeScript check attributes with a hyphen in the name? declare namespace JSX { interface ElementAttributesProperty { props:any; // specify the property name to use } } class A{ props!:{p1:string} } const tsx = <A p1="&q ...

Tips on transferring information from a component to an instance in Vue

My goal is to retrieve data from a component and transfer it to a variable within my root Vue instance. Vue Instance Configuration: new Vue({ el: '#root', data: { searchResultObject: '' }, methods: { // ...

Experiencing a problem with loading scenes on a splash screen using WebGL and three.js

As a newcomer to SOF, I apologize for not being familiar with local customs. // Hello all! I am attempting to develop a 3D model with a splash screen and first-person movement using three.js and its examples. // Here is the source: // The issue at hand ...

When the status is set to "Playing," the Discord Audio Player remains silent

So, I'm in the process of updating my Discord audio bot after Discord made changes to their bot API. Despite my best efforts, the bot is not producing any sound. Here's a snippet of the code that is causing trouble: const client = new Discord.Cl ...

The troubleshooting of a find method in Mongoose

Why is it necessary to use await twice when calling the model function, even though we already used await in the model itself: async function model() { return await data.find({}, '-_id -__v') } When I console.log await data.find({}, '-_id ...

The ngrx/store selector triggers state updates

My state structure is normalized and structured as follows: auth: { user: string; // represents the current logged in uid }; entities: { users: { [key: string]: User } // contains normalized user entities (including the current user) }; User inte ...

What is the best way to select specific points from a THREE.Points object?

I am working on a single THREE.Points() representing a point cloud and I am trying to select individual points using mouse clicks. starsGeometry = new THREE.Geometry(); for ( var i = 0; i < 10000; i ++ ) { var star = new THREE.Vector3( ...

Deactivate Form Group using a custom directive

I'm struggling with implementing a directive that can be applied to elements with the [formGroup] attribute in order to disable the entire form group and its form controls based on a condition, rather than manually calling this.formGroup.disable(). I ...

Creating string unions by combining substrings using template literals

I am looking to streamline the process of deriving a new union from an existing one, without having to explicitly state the string as a parameter each time. The goal is to extract all root strings that end in .bar from a union of translation key strings li ...

Struggling to create horizontal lines on chart.js 3.x. Looking for guidance

Objective I aim to generate a graph with three horizontal lines overlaying my actual dataset line using Chart.js 3.x through CDN integration on my html page. Since I am not utilizing my own Chart.js installation and relying on CDNs instead, integrating t ...