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.
Open this project in Visual Studio Code and install bootstrap by using following command
- npm install bootstrap --save
Now open styles.css file and add Bootstrap file reference. To add reference in styles.css file add this line.
- @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.
- npm install ngx-bootstrap --save
Now open index.html file and add the following cdn link to add css for datepicker.
- <link rel="stylesheet" href="https://unpkg.com/ngx-bootstrap/datepicker/bs-datepicker.css">
Create a new service using the following command
Now open searchdata.service.ts file and add the following lines:
- import { Injectable } from '@angular/core';
- import {HttpClient} from '@angular/common/http';
- import {HttpHeaders} from '@angular/common/http';
- @Injectable({
- providedIn: 'root'
- })
- export class SearchdataService {
- Url: string;
-
- constructor(private http : HttpClient) {
- }
-
- searhhdata(model : any){
- debugger;
- return this.http.post<any>('http://localhost:1141/Api/Searchdata/search',model);
- }
- showdata(){
- debugger;
- return this.http.get<any>('http://localhost:1141/Api/Searchdata/showdata');
- }
- }
Now create a new component by using the following command.
Now open searchdata.component.ts file and add the following code:
- import { Component, OnInit } from '@angular/core';
- import { SearchdataService } from '../searchdata.service';
- @Component({
- selector: 'app-searchdata',
- templateUrl: './searchdata.component.html',
- styleUrls: ['./searchdata.component.css']
- })
- export class SearchdataComponent implements OnInit {
-
- constructor(private searchdataService:SearchdataService) { }
- model : any={};
- emp:any;
- ngOnInit(): void {
- this.showdata();
- }
- showdata()
- {
- this.searchdataService.showdata().subscribe((res: any) => {
- this.emp=res;
- console.log(this.emp);
- })
- }
- searchdata() {
- debugger;
- this.searchdataService.searhhdata(this.model).subscribe((res: any) => {
-
- this.emp=res;
- console.log(this.emp);
- })
- }
- }
Open searchdata.component.html file and add the following lines
- <div class="row">
- <div class="col-sm-12 btn btn-primary">
- How to Search Data Between Two Dates Using Web API and Angular 9
- </div>
- </div>
-
- <form #addClientForm="ngForm" (ngSubmit)="searchdata()" novalidate>
- <div class="row" style="margin-top:10px;margin-bottom: 10px;">
- <div class="col-sm-3 form-group"> </div>
- <div class="col-sm-3 form-group">
- <input
- type="text" #startdate="ngModel" name="startdate"
- [(ngModel)]="model.startdate"
- placeholder="From Date"
- bsDatepicker
- [bsConfig]="{ isAnimated: true }" class="form-control"/>
- </div>
- <div class="col-sm-3 form-group">
- <input type="text" #enddate="ngModel" name="enddate"
- [(ngModel)]="model.enddate"
- placeholder="To Date"
-
- bsDatepicker
- [bsConfig]="{ isAnimated: true }" class="form-control"/>
- </div>
- <div class="col-sm-3 form-group">
- <button type="submit" class="btn btn-success" >Search</button>
- </div>
- </div>
- </form>
-
- <table class="table">
- <thead class="thead-dark">
- <tr>
- <th scope="col">Id</th>
- <th scope="col">Name</th>
- <th scope="col">City</th>
- <th scope="col">JoiningDate</th>
- </tr>
- </thead>
- <tbody>
- <tr *ngFor="let emp of emp">
- <th scope="row">{{emp.Id}}</th>
- <td>{{emp.Name}}</td>
- <td>{{emp.City}}</td>
- <td>{{emp.JoiningDate | date:'yyyy-MM-dd'}}</td>
- </tr>
- <tr *ngIf="!emp||emp.length==0">
- <td colspan="4">
- No Data Found
- </td>
- </tr>
- </tbody>
- </table>
-
-
Now Open app.module.ts file and add the following code.
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
- import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
- import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';
- import { AppRoutingModule } from './app-routing.module';
- import { AppComponent } from './app.component';
- import { SearchdataComponent } from './searchdata/searchdata.component';
- import { FormsModule } from '@angular/forms';
- import { HttpClientModule } from '@angular/common/http';
- @NgModule({
- declarations: [
- AppComponent,
- SearchdataComponent
- ],
- imports: [
- BrowserModule,FormsModule,HttpClientModule,
- AppRoutingModule,BrowserAnimationsModule, BsDatepickerModule.forRoot()
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- 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".
- CREATE TABLE [dbo].[Employee](
- [Id] [int] NOT NULL,
- [Name] [varchar](50) NULL,
- [City] [varchar](50) NULL,
- [JoiningDate] [date] NULL,
- PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
-
- SET ANSI_PADDING OFF
- GO
Create a stored procedure to find the data between two dates.
- CREATE PROC [dbo].[Usp_Empsearch]
- @Fromdate DATETIME,@Todate DATETIME
- AS
- BEGIN
- SELECT * FROM Employee WHERE JoiningDate BETWEEN @Fromdate AND @Todate
- 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.
- public class searchdata
- {
- public DateTime startdate { get; set; }
- public DateTime enddate { get; set; }
-
- }
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.
Now, add two methods to fetch data and search data by based on dates from the database.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using Searchdata.Models;
- namespace Searchdata.Controllers
- {
- [RoutePrefix("Api/Searchdata")]
- public class SearchdataController : ApiController
- {
- employeesEntities DB = new employeesEntities();
- [Route("showdata")]
- [HttpGet]
- public object showdata()
- {
- var a = DB.Employees.ToList();
- return a;
- }
-
- [Route("search")]
- [HttpPost]
- public object search(searchdata sd)
- {
- var a= DB.Usp_Empsearch(sd.startdate, sd.enddate);
- return a;
- }
- }
- }
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:
- EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
- 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
In this article, we learned how to search records between two dates using Web API and Angular 9