Search Data Between Two Dates Using Web API And Angular 9

Introduction

 
In this article, we will learn how to search data between two dates using Web API and Angular 9.
 
Prerequisites
  • Basic Knowledge of Angular 2 or higher
  • Visual Studio Code
  • Visual studio and SQL Server Management studio
  • Node and NPM installed
  • Bootstrap
  • ngx-bootstrap 
Create an Angular project by using the following command.
  1. ng new searchdata  
Open this project in Visual Studio Code and install bootstrap by using following command
  1. npm install bootstrap --save    
 Now open styles.css file and add Bootstrap file reference. To add reference in styles.css file add this line.
  1. @import '~bootstrap/dist/css/bootstrap.min.css';    
To add datepicker we use ngx bootstrap datepicker, so add ngx bootstrap datepicker in this project using the following command.
  1. npm install ngx-bootstrap --save   
Now open index.html file and add the following cdn link to add css for datepicker.
  1. <link rel="stylesheet" href="https://unpkg.com/ngx-bootstrap/datepicker/bs-datepicker.css">   
Create a new service using the following command
  1. ng g s searchdata  
 Now open searchdata.service.ts file and add the following lines:
  1. import { Injectable } from '@angular/core';  
  2. import {HttpClient} from '@angular/common/http';    
  3. import {HttpHeaders} from '@angular/common/http';    
  4. @Injectable({  
  5.   providedIn: 'root'  
  6. })  
  7. export class SearchdataService {  
  8.   Url: string;  
  9.   
  10.   constructor(private http : HttpClient) {  
  11.    }  
  12.     
  13.   searhhdata(model : any){  
  14.     debugger;    
  15.    return this.http.post<any>('http://localhost:1141/Api/Searchdata/search',model);    
  16.   }  
  17.   showdata(){  
  18.     debugger;    
  19.    return this.http.get<any>('http://localhost:1141/Api/Searchdata/showdata');    
  20.   }  
  21. }  
 Now create a new component by using the following command.
  1. ng g c searchdata  
Now open searchdata.component.ts file and add the following code:
  1. import { Component, OnInit } from '@angular/core';  
  2. import { SearchdataService } from '../searchdata.service';  
  3. @Component({  
  4.   selector: 'app-searchdata',  
  5.   templateUrl: './searchdata.component.html',  
  6.   styleUrls: ['./searchdata.component.css']  
  7. })  
  8. export class SearchdataComponent implements OnInit {  
  9.   
  10.   constructor(private searchdataService:SearchdataService) { }  
  11.   model : any={};    
  12.   emp:any;  
  13.   ngOnInit(): void {  
  14.     this.showdata();  
  15.   }  
  16.   showdata()  
  17.   {  
  18.     this.searchdataService.showdata().subscribe((res: any) => {  
  19.       this.emp=res;   
  20.       console.log(this.emp);   
  21.   })  
  22.   }  
  23.   searchdata() {  
  24.    debugger;  
  25.     this.searchdataService.searhhdata(this.model).subscribe((res: any) => {  
  26.             
  27.         this.emp=res;   
  28.         console.log(this.emp);   
  29.     })  
  30.   }  
  31. }  
 Open searchdata.component.html file and add the following lines
  1. <div class="row">    
  2.     <div class="col-sm-12 btn btn-primary">    
  3.    How to  Search Data Between Two Dates Using Web API and Angular 9  
  4.     </div>    
  5.   </div>   
  6.    
  7.     <form #addClientForm="ngForm" (ngSubmit)="searchdata()" novalidate>  
  8.       <div class="row" style="margin-top:10px;margin-bottom: 10px;">    
  9.         <div class="col-sm-3 form-group">  </div>  
  10.     <div class="col-sm-3 form-group">    
  11.         <input  
  12.         type="text" #startdate="ngModel" name="startdate"  
  13.         [(ngModel)]="model.startdate"   
  14.         placeholder="From Date"  
  15.         bsDatepicker  
  16.         [bsConfig]="{ isAnimated: true }" class="form-control"/>  
  17.     </div>     
  18.     <div class="col-sm-3 form-group">    
  19.         <input type="text"  #enddate="ngModel" name="enddate"  
  20.         [(ngModel)]="model.enddate"   
  21.         placeholder="To Date"  
  22.          
  23.         bsDatepicker  
  24.         [bsConfig]="{ isAnimated: true }"  class="form-control"/>  
  25.     </div>    
  26.     <div class="col-sm-3 form-group">    
  27.         <button type="submit" class="btn btn-success" >Search</button>   
  28.     </div>  
  29.   </div>  
  30.     </form>   
  31.   
  32.   <table class="table">  
  33.     <thead class="thead-dark">  
  34.       <tr>  
  35.         <th scope="col">Id</th>  
  36.         <th scope="col">Name</th>  
  37.         <th scope="col">City</th>  
  38.         <th scope="col">JoiningDate</th>  
  39.       </tr>  
  40.     </thead>  
  41.     <tbody>  
  42.       <tr *ngFor="let emp of emp">  
  43.         <th scope="row">{{emp.Id}}</th>  
  44.         <td>{{emp.Name}}</td>  
  45.         <td>{{emp.City}}</td>  
  46.         <td>{{emp.JoiningDate | date:'yyyy-MM-dd'}}</td>  
  47.       </tr>  
  48.       <tr *ngIf="!emp||emp.length==0">  
  49.         <td colspan="4">  
  50.             No Data Found  
  51.         </td>  
  52.       </tr>  
  53.     </tbody>  
  54.   </table>  
  55.     
  56.     
Now Open app.module.ts file and add the following code.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { BrowserAnimationsModule } from '@angular/platform-browser/animations';  
  4. import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';  
  5. import { AppRoutingModule } from './app-routing.module';  
  6. import { AppComponent } from './app.component';  
  7. import { SearchdataComponent } from './searchdata/searchdata.component';  
  8. import { FormsModule } from '@angular/forms';  
  9. import { HttpClientModule } from '@angular/common/http';  
  10. @NgModule({  
  11.   declarations: [  
  12.     AppComponent,  
  13.     SearchdataComponent  
  14.   ],  
  15.   imports: [  
  16.     BrowserModule,FormsModule,HttpClientModule,  
  17.     AppRoutingModule,BrowserAnimationsModule, BsDatepickerModule.forRoot()  
  18.   ],  
  19.   providers: [],  
  20.   bootstrap: [AppComponent]  
  21. })  
  22. export class AppModule { }  
Step 8 - Create database and a table  
 
Open SQL Server Management Studio, create a database named "Employees", and in this database, create a table. Give that table a name like "employee".
  1. CREATE TABLE [dbo].[Employee](      
  2.     [Id] [intNOT NULL,      
  3.     [Name] [varchar](50) NULL,      
  4.     [City] [varchar](50) NULL,      
  5.     [JoiningDate] [dateNULL,      
  6. PRIMARY KEY CLUSTERED       
  7. (      
  8.     [Id] ASC      
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]      
  10. ON [PRIMARY]      
  11.       
  12. GO      
  13.       
  14. SET ANSI_PADDING OFF      
  15. GO       
Create a stored procedure to find the data between two dates.
  1. CREATE PROC [dbo].[Usp_Empsearch]      
  2. @Fromdate DATETIME,@Todate DATETIME      
  3. AS      
  4. BEGIN      
  5. SELECT * FROM Employee WHERE JoiningDate BETWEEN @Fromdate AND @Todate      
  6. END       
Open Visual Studio and create a new project.
 
 
 
 Change the name to Searchdata
 
 
Choose the template as Web API.
 
 
 Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
 
 
Select EF Designer from the database and click the "Next" button.
 
 
 
 Add the connection properties and select database name on the next page and click OK
 
 
 
Check the "Table" and "stored procedures" checkbox. The internal options will be selected by default. Now, click the "Finish" button.  
 
 
 
Our data model is created now.
 
Right-click on the Models folder and add a class searchdata. Now, paste the following code in this class.
  1. public class searchdata  
  2.     {  
  3.         public DateTime startdate { get; set; }  
  4.         public DateTime enddate { get; set; }  
  5.   
  6.     }  
Right-click on the Controllers folder and add a new controller. Name it as "Searchdata controller" and add the following namespace in the Searchdata controller. 
  1. using Searchdata.Models;  
Now, add two methods to fetch data and search data by based on dates from the database.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using Searchdata.Models;  
  8. namespace Searchdata.Controllers  
  9. {  
  10.     [RoutePrefix("Api/Searchdata")]  
  11.     public class SearchdataController : ApiController  
  12.     {  
  13.         employeesEntities DB = new employeesEntities();  
  14.         [Route("showdata")]  
  15.         [HttpGet]  
  16.         public object showdata()  
  17.        {  
  18.             var a = DB.Employees.ToList();  
  19.             return a;  
  20.         }  
  21.   
  22.         [Route("search")]  
  23.         [HttpPost]  
  24.         public object search(searchdata sd)  
  25.         {  
  26.             var a= DB.Usp_Empsearch(sd.startdate, sd.enddate);  
  27.             return a;  
  28.         }  
  29.     }  
  30. }  
 Now, let's enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the "Microsoft.Asp.Net.WebApi.Cors" package. Open Webapiconfig.cs and add the following lines:
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");        
  2. config.EnableCors(cors);   
 Now, go to Visual Studio code and run the project by using the following command: 'npm start'
 
Now select dates from the datepickers and click on search button
 

Summary


In this article, we learned how to search records between two dates using Web API and Angular 9