Ensure that data is properly filtered before being presented in the Angular 5 component

Currently, I am dealing with football data retrieved from an API.

https://i.sstatic.net/MRSsH.jpg

When I make a request to this API endpoint, all the available lists are displayed. My goal is to organize the list based on the game status, such as Finished, Postponed, and Timed.

I attempted to achieve this using the following code:

<div *ngFor="let fixture of fixtures">
    <div *ngIf="fixture.status !== 'FINISHED'">
        <p>{{fixture.date}}</p>
    </div>
</div>

Although it successfully filters out the items from view, the complete filtration isn't achieved. Due to the extensive nature of the list, I only want to display the initial 20 items. Here's what I tried:

<div *ngFor="let fixture of fixtures | slice:0:20">
    <div *ngIf="fixture.status !== 'FINISHED'">
        <p>{{fixture.date}}</p>
    </div>
</div>

The intention was to only show the first 20 filtered items from the list, but unfortunately, it did not work as expected. This is because the original unfiltered list is still present.

It seems my current method of filtering is inefficient. The filtering only applies to the presentation in the view, not to the actual list sourced from the API. Therefore, attempts to slice the list do not yield the desired outcome.

If anyone has suggestions on how I can overcome this issue, your assistance would be greatly appreciated. Thank you in advance.

Answer №1

Avoid using the slice pipe in that way as it may not work well with your *ngIf. The pipe operates on the original list, not the filtered result set.

Before proceeding to a solution, examine the source code of the slice pipe to understand its internal workings:

@Pipe({name: 'slice', pure: false})
export class SlicePipe implements PipeTransform {
  transform(value: any, start: number, end?: number): any {
    if (value == null) return value;

    if (!this.supports(value)) {
      throw invalidPipeArgumentError(SlicePipe, value);
    }

    return value.slice(start, end);
  }

  private supports(obj: any): boolean { return typeof obj === 'string' || Array.isArray(obj); }
}

As evident from the source code, the pipe slices the original list instead of the filtered result set.

Source: Angular.io


To resolve your issue, perform filtering in your component and iterate through the filtered results in your template. Apply the slice pipe only after this step.

This approach is more efficient as it avoids unnecessary loops in the component and allows for additional operations on the filtered lists.

Component:

@Component({...})
export class MyComponent {
    list: any[] = [...];
    fixtures: any[] = this.list.filter(item => item.status !== 'FINISHED');
}

Template:

<div *ngFor="let fixture of fixtures | slice:0:20">
    <p>{{fixture.date}}</p>
</div>

Update:

To address searching issues, search within the original list rather than the filtered list.

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

Error occurred: Unable to locate module: Error: Unable to resolve './templates'

Currently, I am working on a TypeScript file named index.ts which includes some JavaScript code. The main functionality involves importing Bootstrap CSS and templates. import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; import ' ...

Angular 13: Masking User Input with Reactive Form Controls

Looking to incorporate a phone number input field with formatting in a reactive form. The desired format is (123) 456-7890. For reference, check out this example link: https://stackblitz.com/edit/angular13-reactive-form-validation-y1qwmf?file=src/app/app. ...

Creating visual content using Webpack and Angular2

I have a small Angular2 app that utilizes Webpack for project building and scaffolding. One issue I've encountered is the inability to load images specified in TypeScript files during production. After running npm run build, I noticed that these imag ...

Issue with TypeORM @BeforeInsert causing a field in Entity not to be populated with value

Currently, I am facing an issue where I am attempting to update or insert into a token field before the record is saved. However, when utilizing the @BeforeInsert hook, I encounter the following error: "error": "Cannot read property 'co ...

How can I effectively build an Angular Library containing various components?

I am currently restructuring the core elements that form a search page into an angular library. My goal is to include various components in this angular library, such as SearchControls, PageHeader, PageFooter, and more. I intend to insert <search-contro ...

Is pagination available in Material Angular or an alternative solution present?

While exploring ng-bootstrap, I searched through material.angular.io and GitHub for pagination options. I couldn't find anything similar, is there any undocumented component or alternative available? Update: By alternative, I mean using a different ...

What is the best way to alter the Date format in Typescript?

Within my response, the field createdate: "2019-04-19T15:47:48.000+0000" is of type Date. I am looking to display it in my grid with a different format such as createdate: "19/04/2019, 18:47:48" while maintaining its original data type. To achieve this, I ...

Exploring the async/await functionality in TypeScript

Hey there! I'm working with this Angular/TypeScript service, and I've run into an issue where the query part of the function is asynchronous. This means that the return statement gets executed before the data is actually retrieved from the serve ...

`End Angular2 session and close browser tab`

Currently, I am developing a web application using Angular2. I am looking to include a button in the application that, when clicked, will not only close the application but also the browser tab where it was launched. I have been exploring various solution ...

Obtain Value from Function Parameter

In my Angular project, I have a function that is called when a button is clicked and it receives a value as an argument. For example: <button (click)="callFoo(bar)">Click Me!</button> The TypeScript code for this function looks like ...

Adjusting the timeout for a particular operation according to its unique identifier

I am looking for a solution to call a method that posts an answer after an input change in my Angular project. I want to reset the timeout if another input change occurs to avoid multiple posts. Is there a smart way to achieve this? My project involves po ...

Error: Attempted to call the 'post' method on an undefined object, resulting in an Uncaught TypeError. This occurred within the Ionic 2 framework while executing the Javascript code located

While I attempt to convey my message in English, unfortunately, it is not a language I am fluent in. Currently, I am working on an Ionic 2 project. In this particular scenario, I am trying to make an HTTP request using the POST method while emulating it o ...

Utilizing async await allows for the sequential processing of one item at a time within a For loop

Async await has me stumped, especially when it comes to processing items in an array with a 1 second delay: handleArrayProcessing() { clearTimeout(this.timer); this.timer = setTimeout(() => { for (const ...

Ionic datetime returns default values upon initialization

I'm currently in the process of developing an Ionic-Angular-app. I require a datetime component on a page to set the creation date of an object. I am using formGroup for this purpose, but whenever I choose a different date, it always reverts back to t ...

What is the best way to showcase a half star rating in my custom angular star rating example?

component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { projectRating ...

What is the best way to iterate over JSON data from an endpoint that contains multiple nested arrays using the .map() method?

Seeking to showcase weather API data from: () import Image from "next/image" interface Hour { time_epoch: number time: string temp_c: number temp_f: number is_day: number wind_mph: number wind_kph: number wind_deg ...

Angular Service Singleton Utilized in Components

I have a structural question regarding my Angular application. I am following the widely-used core, shared, and feature modules structure, similar to the one found here. In my core module, I have a singleton notification service defined, but I use a custom ...

Executing a function in Angular 2 depending on the class assigned to a <div>

In my HTML code, I am using *ngFor to iterate through an array of messages. <div *ngFor="let message of messages; let i=index" [focused]="i === activeIndex;" [ngClass]="{'message-list-active': activeIndex === i }" (click)="onAddtoMessag ...

Best practice for encapsulating property expressions in Angular templates

Repeating expression In my Angular 6 component template, I have the a && (b || c) expression repeated 3 times. I am looking for a way to abstract it instead of duplicating the code. parent.component.html <component [prop1]="1" [prop2]="a ...

Creating a new list by grouping elements from an existing list

I have successfully received data from my API in the following format: [ {grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"}, {grade: "Grade B", id: 2, ifsGrade: &quo ...