Date picker Angular
Create a date picker field using NgbDatepickerModule angular
Introduction
Datepicker will help you with date selection. There are many types of date pickers but i will use NgbDatepickerModule for this instance. To get started here are easy steps to add date picker field to your project.
Step 1: Add bootstrap to your project if it does not exist
npm i @ng-bootstrap/ng-bootstrap
N.B confirm this by checking your package.json, the versions may vary depending on the version you added to your project.
"@ng-bootstrap/ng-bootstrap": "^10.0.0",
Step 2: Import NgbDatepickerModule to your module.ts. (it can be app module or your custome module)
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgbDatepickerModule } from '@ng-bootstrap/ng-bootstrap';@NgModule({
declarations: [
AppComponent
],imports: [BrowserModule,AppRoutingModule,NgbDatepickerModule,],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Just add ‘NgbDatepickerModule’ on your imports and hover over it to import.
Step 3: Create a form field in component.html
You will get something like
When you click on the icon(box) on the right of the form field
On selecting a date
The next step is to style the calender icon. I added a link of the free version of font awesome to index.html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
Now to style the calender icon, modify the calender button like below
<button class="btn btn-outline-secondary calendar" (click)="date.toggle()" type="button">
<i class="icon-regular fa fa-calendar fa-lg" style="color:rgb(114, 198, 211);" ></i>
</button>
N.B there are other ways of modifying this, explore other options.
As you can notice, this calendar does not show future dates, Today is 7–12–2021 so future dates. This is achieved by adding maxDate property to calender input.
<input
id="registrationDate"
class="form-control"
placeholder="yyyy-mm-dd"
ngbDatepicker
#date="ngbDatepicker"
[maxDate]="maxDate"/>
Define the maxDate in your component.ts file
private today = new Date();
public maxDate = { year: this.today.getFullYear(), month: this.today.getMonth() + 1, day: this.today.getDate() };
Date picker has many properties to modify the calendar dates being displayed. Documentation on limiting dates being displayed to users.
Happy Coding!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!