To use the datepicker in the angular 2 application use ng2-bootstrap
include ng2-bootstrap and moment in your package.json and hit npm install to install both in the node_modules
include datepicker module in your module file. The app.module.ts file will be,
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { DatepickerModule } from 'ng2-bootstrap/ng2-bootstrap';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { DatepickerComponent } from './datepicker.component';
@NgModule({
imports: [ BrowserModule, DatepickerModule],
declarations: [ AppComponent, DatepickerComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Create the text box in html and write the functionality in the ts file like
<div class="container">
<div class="col-md-6">
<label for="datepicker" class="text-primary">Date Picker</label>
<div class="input-group date-picker">
<input type="text" class="form-control" name="datpicker" id="datpicker" placeholder="Date Picker" [(ngModel)]="datePickerValue" (focus)="showDatePicker()" readonly>
<span class="input-group-addon" (focus)="showDatePicker()"><span class="glyphicon glyphicon-calendar" aria-hidden="true"></span></span>
</div>
<div class="dp-popup" *ngIf="isDatePickerShown">
<datepicker [(ngModel)]="datePickerDate" [showWeeks]="false" [maxDate]="today" [ngModelOptions]="{standalone: true}" (selectionDone)="dateSelected($event)"></datepicker>
</div>
</div>
</div>
import { Component, OnInit, ViewChild } from '@angular/core';
import { DatepickerModule } from 'ng2-bootstrap/ng2-bootstrap';
import * as moment from 'moment';
@Component({
selector: 'datepicker-component',
templateUrl: 'datepicker.component.html',
host: {
'(document:click)': 'handleClick($event)'
},
})
export class DatepickerComponent {
isDatePickerShown:boolean = false;
datePickerDate;
datePickerValue;
today:Date = new Date();
constructor() {
}
showDatePicker(){
this.isDatePickerShown = true;
}
hideDatePicker(){
this.isDatePickerShown = false;
}
dateSelected(event){
this.datePickerValue = moment(event).format("YYYY-MM-DD");
this.hideDatePicker();
}
handleClick(event){
if(!(event.target.closest('datepicker') != null || event.target.closest('.btn') != null || event.target.closest('.date-picke') != null)){
this.hideDatePicker();
}
}
}
No comments:
Post a Comment