Datepicker in Angular Forms

In my last article we discuss on how to use Star Rating in angular forms. In these tutorial i discuss on how to add datepicker in our Angular Forms.
First we need to add below line in our app.module.ts file.


.................
//we need to import first Datepicker Module From Bootstrap.
import { BsDatepickerModule} from 'ngx-bootstrap';
...................
@NgModule({
  .........
  imports: [
                BsDatepickerModule.forRoot(),
            ...
           ]
})
export class AppModule(){}



After adding BsDatepickerModule in the app module file. Now we can use these in any component.
Let’s create Basic code for the date-picker elements.


<input type="text"
           placeholder="Datepicker"
           class="form-control"
           bsDatepicker >



import { Component } from '@angular/core';
 
@Component({
  selector: 'datepicker',
  templateUrl: './datepicker.html'
})
export class DatepickerComponent {}


In above example you can easily create date-picker by just adding “bsDatepicker” in input element.
You can also pass the default value “[bsValue]=currentdate”.
We can implement date-range using below code.


<input type="text"
           placeholder="Datepicker"
           class="form-control"
           bsDaterangepicker 
           [(ngModel)]="dateRangeValue"
>



import { Component } from '@angular/core';
 
@Component({
  selector: 'datepickerrange',
  templateUrl: './datepickerrange.html'
})
export class DatepickerRangeComponent {
 dateRangeValue: Date[];
 nextDate = new Date();
 constructor() {
    this.nextDate.setDate(this.nextDate.getDate() + 7);
    this.dateRangeValue= [new Date(), this.nextDate];
  }

}


You can add “Custom date format” to display when calendar date select.
Example:
[bsConfig]=”{ dateInputFormat: ‘YYYY-MM-DD’ }”
[bsConfig]=”{ dateInputFormat: ‘MM/DD/YYYY’ }”
[bsConfig]=”{ dateInputFormat: ‘MMMM Do YYYY, h:mm:ss a’ }”


<input type="text"
           placeholder="Datepicker"
           class="form-control"
           bsDatepicker 
           [bsConfig]="{ dateInputFormat: 'MM/DD/YYYY' }"
>



import { Component } from '@angular/core';
 
@Component({
  selector: 'datepicker',
  templateUrl: './datepicker.html'
})
export class DatepickerComponent {}

You can display Output in below Video

Spread the love
  • 43
  •  
  •  
  •  
  • 3
  •  
  •  
  •