A guide on Using Angular to Filter Data by Date Input

Trying to filter out specific notes created on a selected date. The date format in the db.json files is '2023-08-14' and should match the input format...values are compared in the filter function.

The issue arises as nothing is added to the filtered array, possibly because the input isn't assigned to dateField. When trying to log the value, it appears as undefined. Any idea why it's not being saved? My files are listed below: TS File:

import { Component, OnInit } from '@angular/core';
import { Note } from '../note/notes';
import { NoteService } from '../note/notes.service';
//import {MatDatepickerModule} from '@angular/material';
@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit{
  
  allNotes: Note[] = [];
  filteredNote: Note[] = [];
  dateField: '';
 
  constructor(private service: NoteService){}

  ngOnInit(){
    //retrieve all notes from NotesService

     this.service.getAll().subscribe((data) => {
     this.filteredNote = this.filterDate(data);
     //console.log(this.filteredNote)
     })
  }

  filterDate(data){
    console.log(this.dateField);
    return data.filter(_ => _.date == this.dateField);
  }

}

html File:

<div class="main-container">
    <label for="start">Find a Note from Date Created:</label>
    <body>
          
        <label>
            Enter the Date:
            <input type="date" name="date" [(ngModel)]="dateField">
            <br>
        </label>
    </body>

    <table class="table">
        <thead>
            <tr>
                <th scope="col">Id</th>
                <th scope="col">Title</th>
                <th scope="col">Body</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let note of filteredNote">
                <th scope="row">{{ note.id }}</th>
                <th>{{ note.title }}</th>
                <th>{{ note.body }}</th>
            </tr>
        </tbody>
    </table>
</div>

Answer №1

The filtering process in this implementation only occurs once on the notes retrieved from the service, preventing the user from altering the value of dateField. To allow for dynamic changes, it is recommended to link an event handler using the (change) attribute. More information can be found at https://angular.io/guide/lifecycle-hooks#onchanges

Answer №2

Learn about the ngModelChange event that triggers the filterDate function whenever a user modifies the input.


    <label>
        Enter the Date:
        <input type="date" name="date" [(ngModel)]="dateField" (ngModelChange)="filterDate($event)" >
        <br>
    </label>

Retrieve entire JSON data during ngOnInit and perform filtering when the date field is modified by the user.

 completeData:any[]=[];
  ngOnInit(){
    //fetch all notes from NotesService

     this.service.getAll().subscribe((data) => {
     this.completeData=data;
     })
  }

  filterDate(changeddate:any){
    this.filteredNote = this.completeData.filter(_ => _.date == changeddate);
  }

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

Can you explain the variance between Next.js and Create React App?

I've been curious about understanding the distinctions between Next.js and Create React App (CRA). Both aim to simplify our lives when developing front-end applications with React. While researching online, I came across a key difference: Next.js o ...

What is the best way to search through an array in TypeORM?

I am working on implementing user permissions management using TypeORM with PostgreSQL. The permissions are defined within the user entity in the following column: @Column({ type: 'text', array: true }) permissions: UserPermission[] = []; Th ...

"An error has occurred: ENOENT - The specified file or directory does not exist, cannot create directory" on the live website

I am facing an issue on my website where I need to create a folder and save some files in it. While the code works perfectly fine locally, once deployed on render, I encounter the following error: Error: ENOENT: no such file or directory, mkdir '/opt/ ...

Utilizing Threejs to implement dynamic text labels

Recently, after reading a discussion on stackoverflow, I decided to incorporate labels into my canvas. To achieve this, I created a second scene and camera to overlay the labels on top of the first scene. this.sceneOrtho = new THREE.Scene();//for labels t ...

Struggling for hours with a nested React component that refuses to render

I'm new to the world of react and javascript development and currently encountering an issue with nesting a component. While the Home component is displaying correctly, the testComp is not appearing as expected. I'm feeling quite stuck and would ...

NextJS React - WebpackError: Cannot access 'window' before initialization

I'm delving into the world of React and recently completed the "Getting Started" tutorial for NextJs (link), successfully setting up a new project. However, when attempting to import third-party plugins like current-devices or smooth-scrollbar, I enc ...

Tips for adding or updating query parameters in Angular2

When navigating and updating settings in my app, I am utilizing query parameters that I need to retain and update. Adding a parameter is simple using the following method. onNavigate() { this.router.navigate(['reports'], {queryParams: {'rep ...

Having trouble getting tailwind dark mode to work on next.js?

I have set up a custom boilerplate using next.js(10.0.5) with preact(10.5.12), typescript(4.1.3), and tailwind(2.0.2). I am attempting to incorporate a dark mode feature from Tailwind. I followed the instructions from next-themes in order to add the dark ...

Exploring Json parsing in Python with Django

I am currently using Django for my web application. I am facing an issue where I cannot access Nodes and edges by calling decoded_data['nodes']. Instead, I am encountering the error message: 'NoneType' object is not subscriptable Thi ...

When Socket.emit is called, it outputs <span> elements within a well-structured message

Currently working on a small chat application using Node.js, Express.js, and Socket.IO. However, I'm encountering an issue with formatting. Instead of displaying the message content within <span> tags as intended, it is printing out the actual t ...

The Firefox tab continues to load endlessly due to an embedded iframe

As I test an HTML page on Firefox Developer, I encounter an issue with an iframe. While the iframe works fine on Google Chrome, it causes the parent page to continuously load on Firefox. This leads to a degradation in performance after a few minutes. The i ...

Adjust the variable's value

After clicking on the "Add to Cart" button, the value is added to ".total-cart". When an option is selected in , its value is also added to the total cart value and displayed in ".total-all". However, clicking "Add to Cart" again does not update the value ...

I want to hide jqvmap when viewing on mobile devices

I'm currently working on my website at . I have a template that I'm using as a guide, but I want to make the map disappear on mobile view and replace it with a dropdown list. Can anyone suggest what code I should use for this? Appreciate any hel ...

Don't forget to save the toggleClass state to local storage in jQuery so it persists after

It's a challenge to maintain the value of toggleClass after refreshing or reloading the page. I have a structured table where rows toggle visibility when clicked. To preserve these toggle values, I utilized localStorage, but unfortunately, the state i ...

Generate an object in Typescript that includes a dynamic property calculated from an input parameter

Is there a way to achieve the following function in TypeScript? function f<T extends 'a' | 'b'>(t : T): {[t]: ...} { return {[t]: ...} } This code is intended to make f('a') have type {'a': ...} and similarl ...

How to Change a Property in a Child DTO Class in NestJS with Node.js

I am working with enums for status: export enum Status { Active = "Active", Inactive = "Inactive", } Additionally, I have a UserStatus enum: export enum UserStatus { Active = Status.Active, }; There is also a common dto that inc ...

Mapping an array of objects using dynamically generated column names

If I have an array of objects containing country, state, city data, how can I utilize the .map method to retrieve unique countries, states, or cities based on specific criteria? How would I create a method that accepts a column name and maps it to return ...

Error TS2451 in GatsbyJS: "react_1" block-scoped variable cannot be redeclared

Trying to implement typescript with custom routes in gatsbyjs: require("source-map-support").install(); require("ts-node").register(); exports.createPages = require("./src/createPages"); tsconfig.json { "include": ["./src/**/*"], "compilerOptions": ...

Having trouble integrating SVG icons into my Angular project

I'm encountering an issue with adding icons that I've designed in Figma to my web application. Some of the icons are displaying correctly while others are not. Here is the code snippet I am using to add the icons: .dx-icon-info { mask-image: ...

Mobile site experiencing slow scrolling speed

The scrolling speed on the mobile version of my website, robertcable.me, seems to be sluggish. Despite conducting thorough research, I have not been able to find a solution. I have attempted to address the issue by removing background-size: cover from my ...