Facing issue with Angular 17 where pipe is displaying empty data

I am currently utilizing Angular 17 with the code provided below:

database.component.html

@for(user of (users | userPipe:filters); track user.id) {
    <tr id="{{ user.id }}">
        <td>{{ user.name }}</td>
        <td>{{ user.surname }}</td>
        <td>{{ user.age }}</td>
    </tr>
}
@empty {
    <tr>
        <td colspan="3">Empty</td>
    </tr>
}

filters contains a string array that holds keywords used for filtering database entries.

database.pipe.ts

@Pipe({
    name: 'userPipe',
    pure: false
})
export class databasePipe implements PipeTransform {
    transform(values: Users[], filters: string[]): Users[] {
        
        if (!filters || filters.length === 0 || values.length === 0) {
            return values;
        }

        return values.filter((value: User) => {
            filters.forEach(filter => {
                const userNameFound = value.name.toLowerCase().indexOf(filter.toLowerCase()) !== -1;
                const userSurnameFound = value.surname.toLowerCase().indexOf(filter.toLowerCase()) !== -1;
                const ageFound = value.age.toLowerCase().indexOf(filter.toLowerCase()) !== -1;

                if (userNameFound || userSurnameFound || ageFound) {
                
                    console.log("value: ", value);
                    return value;
                }
                return "";
            });
        });
    }
}

The functionality works as expected and I can observe matched entries in the browser console using value: <value>. However, despite this, my filtered table only displays "Empty" without any data shown. Do you happen to know the reason behind this issue?

Answer №1

The logic for your filter in the databasePipe function is not correct. Instead of returning a boolean value (predicate) to indicate whether the element is selected, you are returning undefined which is a falsy value. This will cause your table to display the @empty template.

To fix this issue, you should use the .some() method so that it returns true when any of the filters are met.

return values.filter((value: User) => {
  return filters.some((filter) => {
    const userNameFound =
      value.name.toLowerCase().indexOf(filter.toLowerCase()) !== -1;
    const userSurnameFound =
      value.surname.toLowerCase().indexOf(filter.toLowerCase()) !== -1;
    const ageFound =
      value.age.toLowerCase().indexOf(filter.toLowerCase()) !== -1;

    return userNameFound || userSurnameFound || ageFound;
  });
});

Check out the demo on StackBlitz

Answer №2

A return statement cannot be used inside a forEach loop because the function will continue executing.

Instead, you can achieve similar functionality by using the following approach:

return values.filter((value: User) => {
    let find=false; // initially set to false
    filters.forEach(f => {
        const userNameFound = value.name.toLowerCase().indexOf(f.toLowerCase()) !== -1;
        const userSurnameFound = value.surname.toLowerCase().indexOf(f.toLowerCase()) !== -1;
        const ageFound = value.age.toLowerCase().indexOf(f.toLowerCase()) !== -1;

        // if any of the filter criteria match, set find to true
        if (userNameFound || userSurnameFound || ageFound) {
            find= true;
        }
    });
    return find;
});
}

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

Warning: The TypeScript version in use may not support all features. The current language level is set to XX in Visual Studio 2019

After installing VS 2019, I noticed that Microsoft.TypeScript.MSBuild 4.2.3 was added. On my Windows 10 OS, I also installed it using NPM in the following way: However, upon opening VS 2019, I encountered the warning below: TypeScript 3.4 feature Curre ...

Accessing the value of an object nested within another object in Angular

I have encountered numerous similar topics, but after going through all of them, I still cannot pinpoint what I am doing incorrectly. The data I retrieve is from DEXIE (indexedDB) where my record is stored in the following format: async addRequestToLocalD ...

Using the spread operator to modify an array containing objects

I am facing a challenge with updating specific properties of an object within an array. I have an array of objects and I need to update only certain properties of a single object in that array. Here is the code snippet I tried: setRequiredFields(prevRequir ...

Accessing the Dependency Injector in Angular 6 with renderModuleFactory

How can I access the dependency injector in order to retrieve a service instance within renderModuleFactory? I am trying to do this in the main.server file to ensure the correct HTTP status code is returned for server-side rendering. Unlike NodeJs, ASP.ne ...

How can dependencies for an entire class or module be mocked in the mocha ecosystem similar to jest.mock?

I am currently working on unit testing a module that resembles the following code structure: import { Countdown } from "./database/orm"; export class PersistentTimer { protected constructor(...) { ... } // To ensure database writing ...

How can we ensure a generic async function with a return type that is also generic in Typescript?

I'm currently working on a function that retries an async function multiple times before rejecting. I want to make sure the typescript typings of the retry function are maintained and also ensure that the passed function is of type PromiseLike. Creat ...

What is causing the router.events to not fire for FooComponent in my Angular project?

Upon opening the following link , the eventsFromFoo entries in the console are nowhere to be found. It appears that this.router.events is failing to trigger for FooComponent. Any insights on why this might be happening? I am in urgent need of capturing t ...

Bootstrapping Angular2 asynchronously using an external JSON configuration file

After upgrading to angular2 RC6, I am facing a challenge in loading an external JSON config file before bootstrapping my AppModule. It was working fine with RC5 but now I am struggling to find the equivalent way of injecting this data. /** Create dummy XS ...

Perform a delayed evaluation of the length of the @Input() array

In my Component, I am utilizing an @Input() ids: string[] = []; variable to check if the length equals 1 in the DOM. <mat-expansion-panel *ngFor="let id of ids" [expanded]="ids.length === 1"> ... </mat-expansion-panel> However, when I append ...

Learn how to easily set a radio button using Angular 4 and JavaScript

It seems like a simple task, but I am looking for a solution without using jQuery. I have the Id of a specific radio button control that I need to set. I tried the following code: let radiobutton = document.getElementById("Standard"); radiobutton.checke ...

Steps for implementing an onclick action in Angular 4 from infowindow content

Currently, I am integrating Google Maps into an Angular 4 project and I need to implement a click event inside the infowindow. How can I achieve this? I attempted the following code but encountered an issue where the name is undefined. Even though I called ...

Design a Dynamic Navigation Bar with Angular Material to Enhance User Experience

I've put together a toolbar with Angular Material, but I'm facing responsiveness issues. How can I ensure the toolbar is responsive? Check out the code for the toolbar below: <md-toolbar color = "primary"> <button md-button class=" ...

What is the best practice for inserting typescript definitions and writing them when the object already has a pre-existing definition?

Apologies for this question, as I am struggling to find the necessary information due to my limited understanding of Typescript. I have integrated a jquery plugin called typeahead and added a global variable named bound on the window object for communicati ...

Why isn't my Bootstrap affecting Angular?

Hello, I am currently working on a project using Angular. Recently, I installed Bootstrap and added it to angular.json, but unfortunately, the changes did not take effect even after restarting the app. Here is the code snippet that I am currently using: h ...

Set the subscription's value to the class property without changing its original state

Lately, I have been using the following method to set the value of a subscription to a property in my classes: export class ExampleComponent implements OnInit { exampleId: string; constructor(public route: ActivatedRoute) { this.route.params.subs ...

Transferring data types to a component and then sending it to a factory

I have been grappling with creating a factory method using Angular 2 and TypeScript. However, my attempts have hit a roadblock as the TSC compiler keeps throwing an unexpected error: error TS1005: ',' expected. The issue arises when I try to pa ...

Send the index of the row to the event handler in the table of data

I am currently utilizing a data table component from PrimeNG and have the following template code: <p-column [style]="{'width':'40px'}"> <template let-col let-rowData="rowData" let-rowIndex="rowIndex" pTemplate type="body" ...

Resolving TypeScript error: Property 'Error' does not exist on type 'Angular2 and Objects'

One of the models I am working with is called "opcionesautocomplete.model.ts" interface IOpcionesAutocomplete { opcionesStyle: OpcionStyle; pcionPropiedades: OpcionPropiedades; } export class OpcionesAutocomplete implements IOpcionesAutocomplet ...

Encountering "token_not_provided" error message on all GET routes in Laravel 5.3 with JWT authentication

I'm currently working on implementing authentication using Laravel 5.3 and Angular 2 with JWT. The authentication part is functioning properly, and I am able to successfully obtain the token. However, when attempting to navigate to any GET routes, an ...

The CoreUI Sidebar gracefully hovers over the main page content

I recently started using CoreUI to design the layout for my application, but I ran into an issue while trying to integrate the Sidebar. Although the Sidebar is visible on the left side, I'm having trouble making sure that the router-view takes up the ...