failure of pipe during search for art gallery information

Hi, I've created a filter pipe to search for imagenames and imageids among all my images. However, it seems to only find matches in the first image. There seems to be something wrong with my code.

This is my FilterPipe class in filter.pipe.ts where I have implemented the search method:

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

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(value: any, arg: any): any {
    if (arg === '' || arg.length < 1) return value;
    const resultPosts = [];
    for (const imagen of value) {
      if (imagen.name.toLowerCase().indexOf(arg.toLowerCase()) > -1) {
        resultPosts.push(imagen);
      } else if (imagen.imagenId.toLowerCase().indexOf(arg.toLowerCase()) > -1){
        resultPosts.push(imagen);
    };
    return resultPosts;
  }
  }
}


In my list.component.html where I have an input field for searching:

<div class="row">
  <form class="form-inline my-2 my-lg-0">
    <input class="form-control mr-sm-2" type="text" name="filterImagen" placeholder="Search" [(ngModel)]="filterImagen"> 
    <button class="btn btn-primary my-2 my-sm-0" type="submit">Search</button>
  
  </form>
    <div class="col-md-4" *ngFor="let imagen of imagenes | filter:filterImagen; index as i">

//when I look for the imagename or imageid, it just looks if my first image has the name I write on the searchbar

      <div class="card mb-3 animated zoomIn">
            <h3 class="card-header">{{imagen.name}}</h3>
            <div class="card-body">
              <h5 class="card-title"><b>ID: </b>{{imagen.imagenId}}</h5>
            </div>
            <div class="card-body text-center">
            <img style="height: 200px; width: 100%; display: block;" src="{{imagen.imagenUrl}}" alt="Card image">
            </div>
          </div>
    </div>
</div>

/* In my list.component.ts, I have declared a variable filter like this: */

imagenes: Imagen[] = [];

filterImagen = '';  //just declared it here

//I already imported my FormsModule on app.module.ts and my classes.

Answer №1

Make sure you added the pipe correctly in Declarations. Alternatively, consider exporting it from a module and importing that module into app.module.

UPDATE - I found the issue :) You need to move return resultPosts outside of the for-loop.

If you'd like, I've improved the clarity of the pipe with this refactored code:

import { Pipe, PipeTransform } from "@angular/core";
import { Imagen } from "./app.component";

@Pipe({
  name: "filter"
})
export class FilterPipe implements PipeTransform {
  transform(value: Imagen[], arg: any): any {
    if (arg === "" || arg.length < 1) return value;

    return value.filter(imagen => imagen.name.toLowerCase().indexOf(arg.toLowerCase()) > -1 ||
        imagen.imagenId.toLowerCase().indexOf(arg.toLowerCase()) > -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

The EJS view fails to render when called using the fetch API

Within my client-side JavaScript, I have implemented the following function which is executed upon an onclick event: function submitForm(event) { const data = { name, image_url }; console.log(data); fetch('/', { method: &apo ...

I'm having trouble locating the module "script!foundation-sites/dist/foundation.min.js on Heroic."

This is the content of my webpack.config.js file: var webpack = require('webpack'); var path = require('path'); process.env.NODE_ENV = process.env.NODE_ENV || 'development'; module.exports = { entry: [ 'script!jque ...

The toast feature is struggling to locate its designated div

Hey there, I've encountered an issue where the toast alert doesn't display on the page after I log in, but it does show up when I sign out. Any thoughts on why this is happening? I've tried various things like logging the toastLiveExample an ...

Troubleshooting Mobile App Errors with Rails API

My mobile application is connected to a Rails server. I am encountering an issue when attempting to edit an Item in the Rails database using a JSON request from my application. The first time I make the AJAX request, I receive an error message. {"readySta ...

Attempting to create an array using jQuery's :checked selector

In my table structure below, I have multiple rows with various data: <tr class="row"> <td class="row-checkbox-delete-row"> <input tabindex="-1" class="checkbox-delete-row" type="checkbox" /> </td> <td class="r ...

Uploading Files with Vuetify 2 v-file-input and AxiosIn this tutorial, we

After researching extensively on the topic, I reviewed questions such as file-upload-in-vuetify and vuetify-file-uploads, but unfortunately, the solutions provided did not work for me. My current challenge involves utilizing Vuetify 2's <v-file-in ...

Running a Custom Tab Component in a React Application

I am currently facing an issue with my React app that has multiple tabs. When I click on a specific tab, I want only that tab to render, but currently all tabs are rendering when I click on one. I have used console.log to confirm that all tabs are indeed r ...

yet another scenario where the component's state changes without the component reflecting those changes

My react component includes a state variable called: showEditor When showEditor is set to false, the component should display a div containing a number (initially showEditor is false). If the state variable is true, the component should display a textbox ...

Looking to utilize Axios in React to make API calls based on different categories upon clicking - how can I achieve this?

My current issue involves making an API call upon clicking, but all I see in my console is null. My goal is to have different API categories called depending on which item is clicked. const [category, setCategory] = useState(""); useEffect(() => { ...

In Photoshop scripting, trying to manipulate an undefined object is like trying to find

I am facing an issue in Photoshop while trying to create a grommet using a script. The error message I receive is: Error: undefined is not an object line 63 ( grommetMarkL = printMarksLayer.pathItems.ellipse( -(spacingY), spacingX, grommetSize, gromm ...

Unlocking the potential of Vue within shadow dom environments

I am facing an issue with a shadow DOM that includes the root element and a Vue component. <template> <div class="container"> <div id="app"></div> </div> <script src="http://my-site.com/app/js/vue-compo ...

Having trouble populating a dropdown menu with states based on a selected country in real time

I'm attempting to create a dynamic dropdown where selecting a country will populate the states. I have all the necessary data stored in two tables, but I'm unsure how to proceed. While I can easily generate the initial list of countries, handling ...

"Encountering a hang while using the .save() function and only

Issue with storing data in MongoDB This is only my second attempt at saving data to a database and I am still relatively new to the process. I have a form on my HTML page that sends string data to be saved in a MongoDB database. I successfully connected t ...

Every time I try to utilize "useCallback," it results in a TypeError error popping up

I am struggling with an issue related to a const experience that involves creating 6 experiences with their respective popovers. I have been instructed to use useCallback, but every time I attempt to do so, I encounter an error message. This relates to my ...

Confused between Javascript and PHP? Here's what you should consider!

Looking for a solution to transfer a string from JavaScript, obtained from the content of a div, to PHP in order to create a text file with this information. What would be the most effective approach to accomplish this task? Edit[1]: Using the Post ...

Unveiling the solution: Hide selected options in the input field of Material UI Autocomplete in React

I need help with not displaying the labels of selected options in the input field. I think it might be possible to do this using the renderInput property, but I'm not sure how. Even with the limitTags prop, the options still show up in the input field ...

What is the best way to extract data from user input and display it in a table modal?

I need to retrieve all the values from the 'input' fields and display them in a modal table using JavaScript. What is the best way to achieve this? Here is my current script: <script> $(document).ready(function() { ...

Having Trouble with QR Code Generator Functionality

UPDATE: The initial code has been updated to implement the recommendations provided. I am currently working on a QR Code generator that updates every minute. Although I have developed the code below, I am encountering some errors and could use some assist ...

Issue with Vuetifyjs theme variable failing to function properly in version 1.0.0

Check out the step-by-step instructions provided in https://vuetifyjs.com/en/style/theme. I successfully changed the theme using the code below with vuetifyjs version 0.13.0. However, after updating to vuetifyjs 1.0.5, the font still displays correctly bu ...

`Moving smoothly with a slider and then reversing direction`

I have implemented a range slider to control the value in an input field. The values can vary greatly, so I needed finer control for lower numbers that gradually expands for larger numbers. To address this issue, I utilized an easing equation based on the ...