Guide on designing a date range search filter using Angular

Hello Stack Overflow community.

I am currently working on a date range filter pipe in Angular to fetch data from an API. However, I'm facing an issue where the filter is not displaying any data after applying it.

The data is being fetched from Firebase:

Below is the service responsible for fetching the data:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class FacturasService {

  constructor(private http: HttpClient) { }

  getFacturas() {
    return this.http.get('https://loggin-app-fa0a7.firebaseio.com/data/facturas.json');
  }
}

Additionally, here is the pipe used to filter the data based on a date range:

...

Lastly, this snippet shows how the pipe is applied within the component:

...

If you would like to view the whole project, please visit:

https://stackblitz.com/edit/github-necjgp?file=src%2Fapp%2Fservices%2Ffacturas.service.ts

Any help or guidance from the SO community would be greatly appreciated. Thank you!

Answer №1

Check out the demo I discovered a few issues in the code. One of them is within the for loop where you should use filteredRow instead of row, and another issue is with the missing conversion of dates, which should be done like this: new Date(filteredRow.fecha). Additionally, I encountered problems when adding and removing dates.

To address these issues, I replaced the for loop with the filter method and made improvements by implementing controls to handle date input removal.

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'filtroFecha'
})
export class FiltroFechaPipe implements PipeTransform {
  transform(row: any, f1: Date, f2?: Date): any {
    if(f1.toString().length == 0) f1 = new Date("1995-12-25T11:30:00.000Z");
    f2 == null ? f2 = new Date() : f2; 
    if (f1 >= f2 || f1 == null) { return row;}
    return row.filter(x => {return new Date(x.fecha) >= new Date(f1) && new Date(x.fecha) <= new Date(f2)});   
  }
}

Answer №2

I modified the Pipe code to improve its functionality:

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

@Pipe({
  name: 'filtroFecha'
})

export class FiltroFechaPipe implements PipeTransform {

  transform(row: any, f1: Date, f2?: Date): any {

const resultadoFiltro = [];
let date1 = new Date(f1);
let date2 = new Date(f2);
// Check if date is within range
if (f1 >= f2 || f1 == null) {
  return row;
}
// Set current date if end date is invalid
if (f2 == null) {
  f2 = new Date();
}
// Create new array if both dates are correct
for (const filteredRow of row) {
  let a = new Date(filteredRow.fecha);

  if (a > date1 && a <= date2) {
    resultadoFiltro.push(filteredRow);
  }
}
return resultadoFiltro;
  }
}

With these changes, the Pipe now functions correctly by comparing Dates instead of strings.

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

Send the array within the "data" attribute when making a Bootstrap AJAX request on the server side

I'm struggling to determine if I can include an array in the data tag within my client JS code. Here's a snippet of the code: $.ajax({ url: '/mobiledoc/jsp/aco/Beneficiary/ptmmview.jsp', data: { "action":"savePatientRec ...

Is there a way to clear the email form after submitting it, allowing for another email to be sent seamlessly without the need to refresh the

I have been experimenting with a contact form on my Wordpress website. It's functional, but here's the issue... Upon page load, the contact form is empty (obviously). If the text fields are left blank, the form will not send (also obvious). W ...

Is the use of addEventListener("load",... creating an excessive number of XmlHttpRequests?

Consider a scenario where you have the following JavaScript code running in a Firefox plugin, aimed to execute an XmlHttpRequest on a page load: function my_fun(){ var xmlHttpConnection = new XMLHttpRequest(); xmlHttpConnection.open('GET', ...

jQuery failing to trigger onClick event for a specific group of buttons

Javascript: <script> $(document).ready(function(){//Implementing AJAX functionality $(".acceptorbutton").on('click', function(){ var whichClicked = this.attr('name'); ...

How to Use an Object Created from a Different Class in TypeScript

Scenario In the development process, I am using an auth.service.ts. This service is responsible for fetching user information from the database upon login. The retrieved data is then used to create a new user object. Here is a snippet of the code: user: ...

Problem with the Auto-fill Feature in PrimeNG Module

Check out my code on Gist:   https://gist.github.com/rickymuvel/8ddc4d14d90877329447ddde9c0aa835 The issue I'm facing involves the Autocomplete module in PrimeNG. It seems that the specific path in the ubigeo.service.ts file is not being called. Her ...

Troubleshooting Challenges in JavaScript/jQuery Hangman Game

Having trouble with my hangman game's game loop. Attempting to replace correct letters as the game runs through the word, but it's currently: looping through the word checking if the guessed letter is in the word returns index[0] Tried splitti ...

Transform a current ASP.NET Core 2.1 Angular application into Angular 6 using Angular CLI 6

I recently developed an ASP.NET Core 2.1 Angular web application using Angular Version 5.2, but now I want to upgrade it to Angular 6 along with Angular CLI 6. Here are the steps I followed for the upgrade: Started by creating the project in Visual Studio ...

Creating a Date Computation Tool that Adds Additional Days to a Given Date

I have a challenge where Date 0 represents the start date, Date 1 is the result date after adding a certain number of days (NDays). I am looking for help in JavaScript to calculate Date0 + NDays = Date1. Please assist me as my coding knowledge is quite l ...

Is it possible to wait for two asynchronous actions using only one await statement?

I have a situation where I am dealing with a node module that exports a promise to resolve a database connection. Once this connection is resolved, I then need to use it to query records which involves another asynchronous operation. Is it possible to hand ...

Encountering a 404 error when trying to retrieve parameters in Express JS

I am attempting to save a file by sending it as a JSON string through an ExpressJS POST request: app.post('/filewrite/', (req, res) => { const fs = require('fs'); console.log(req.body); fs.writeFile("./db/test.json", req.body, ...

JavaScript group by first letter issueI am facing a problem when trying

Having an issue with my code that needs to group contacts by first letter: A. ADRIAN ANDREI ANGEL B. BENY BORRIS Z. ZEYN etc. The current code is not displaying the groups correctly. I want to list each contact under its initial letter. Below is ...

The function is able to retrieve the previous value stored in the state array

Currently, I am working on creating a test app which is a simple address book. The app is nearly complete, but I am encountering an issue with selecting items from the FlatList component. Upon longPressing a contact, it triggers the onLongPress function ...

Issue with React Native Hook where converting a function into a class variable results in 'undefined'

We are currently in the process of converting a react native function into a class so that we can implement state management compatible with Firebase's real-time database. It recently came to our attention that Hooks cannot be used within a class, so ...

Tips for keeping a checkbox checked on page refresh in React JS

I am facing an issue where the checkbox, which was checked by the user and saved in local storage, is displaying as unchecked after a page refresh. Even though the data is stored in local storage, the checkbox state does not persist. The code I am using i ...

Encountering problem with ngx material timepicker field within a mat dialog

When utilizing the ngx material timepicker field in a mat dialog, I am encountering an issue where the data is correctly mapped to the form group and the time displays properly when opening the clock view. However, the time does not display correctly on th ...

Error message: Angular model displaying nested Typescript object within object has encountered an issue

I've defined the following class as a model in Angular export class Product { constructor(private name: string, private data: { price: number, discount: number }) { } } and created an instance of it in a component like so: product: Product = new ...

Unable to fetch QueryParameters in Angular 14

I recently developed a new Angular 14 application where I created a simple component named TestComponent. In the routing.module.ts file, I set up the following route: const routes: Routes = [{ path:'test', component: TestComponent }] The issue ...

I am struggling to make the map method display the specific components I need

Attempting to create a scalable Custom Form using an array of objects and a custom Input field in a React-Typescript project import React, { ChangeEvent } from "react" import { InputField } from "./InputField" interface FormItem { ...

Is it possible to save user inputs in a .json file for future use, and retrieve and reuse them in subsequent sessions or processes?

I am currently developing an account generator using puppeteer and I have a specific requirement for user inputs. The script prompts the user to input necessary variables, but I am interested in exploring the possibility of storing these inputs in a JSON ...