So I am trying to select a date input, and use that input to filter out specific notes that were created on that date. My date format is ‘2023-08-14’ in my db.json files for these notes and the input format I believe is the same…I compare this values in the filter function.
The problem is that nothing is getting added to the filtered array, and I believe it is because the input is not being assigned to dateField. I tried to console.log the value but it is undefined. Any reason to why it is not being saved?
My files are 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);
//console.log("here")
//find the one with the matching value from "date" input
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>
2
Answers
This implementation only filters the notes returned by the service once, so the user won’t have a chance to change the value of
dateField
. It may help to bind to declare an event handler bound(change)
to filter. https://angular.io/guide/lifecycle-hooks#onchangesIntroduce ngModelChange so that whenever user changes the input filterDate function is triggered.
Taking enirre json on ngOnInit and whenever a user changes the datefield filtering wil be done.