Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Angular datepicker tutorial

Suggested Videos
Part 8 - Bootstrap checkbox in angular | Text | Slides
Part 9 - Angular bootstrap select list | Text | Slides
Part 10 - Angular select options from array | Text | Slides

In this video we will discuss
  • Why is not a good practice to use the browser built-in DatePicker control
  • Installing ngx-bootstrap 
  • Using ngx-bootstrap datepicker in Angular

Why is not a good practice to use the browser built-in DatePicker control : This is because the implementation of datepicker is different from browser vendor to vendor. This means our end users may have different experience depending on the browser they use. Let us understand this with an example.


On our "Create Employee" form we want to capture Date of Birth of an employee. Datepicker control is very useful in capturing dates from users. When we use the HTML5 input type date, the browser automatically displays it's built-in datepicker control. Include the following piece of HTML on "create-employee.component.html" file just below the "Department" field HTML

<div class="form-group">
  <label for="dateOfBirth">Date of Birth</label>
  <input id="dateOfBirth" name="dateOfBirth" [(ngModel)]="dateOfBirth"
          type="date" class="form-control" />
</div>

Notice we have set the input element type to date. At this point if we run the project and navigate to http://localhost:4200/create in Google chrome, we see the date-picker as shown below.
angular datepicker example

Now, if we navigate to the same url in firefox, we see a date-picker control that is very different from the date-picker control that is on Google chrome browser.
angular bootstrap datepicker

So, this means our end users have different experience depending on the browser they use. What we want here is consistency. There are many third party Date-picker controls that we can use, to provide consistent experience to our end users. ngx-bootstrap datepicker control is one of them.

Please refer to the UI components section on the following page, to see the list of all third party UI components that we can use in Angular
https://angular.io/resources

Installing ngx-bootstrap : The following are the steps to install ngx-bootstrap 

Step 1 : Execute the following command to npm install ngx-bootstrap
npm install ngx-bootstrap --save

Step 2 : If you do not have Bootstrap installed, please install it using the following npm command. If you are following along we have already installed bootstrap in Part 1 of this Angular CRUD tutorial. So I am not going to execute this command again.
npm install bootstrap@3 --save

Please note : We are usng Bootstrap 3. We can also use Bootstrap 4 with ngx-bootstrap. Please refer to the documentation available at the following link on how to use Bootstrap 4 with ngx-bootstrap.
https://valor-software.com/ngx-bootstrap/#/getting-started

Step 3 : Once Bootstrap is installed, open .angular-cli.json file and specify the path to the Bootstrap stylesheet (bootstrap.min.css) in the styles property as shown below. Again, we have already done this in Part 1 of Angular CRUD tutorial.
"styles": [
  "../node_modules/bootstrap/dist/css/bootstrap.min.css",
  "styles.css"
]

Using ngx-bootstrap datepicker in Angular : The following are the steps to use ngx-bootstrap datepicker in Angular

Step 1 : In app.module.ts file, include the following import statement to import BsDatepickerModule 
import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';

Also, include BsDatepickerModule in the imports array of @NgModule decorator as shown below
@NgModule({
  imports: [BsDatepickerModule.forRoot(),...]
})

Step 2 : In "create-employee.component.html" file, make the following 2 changes to the HTML that displays the "Date of Birth" field
  • Change the "type" attribute value from "date" to "text"
  • Include "bsDatepicker" directive on the input element
<div class="form-group">
  <label for="dateOfBirth">Date of Birth</label>
  <input id="dateOfBirth" name="dateOfBirth" [(ngModel)]="dateOfBirth"
          type="text" bsDatepicker class="form-control" />
</div>

Step 3 : Include a reference to the bs-datepicker.css file in .angular-cli.json file.

"styles": [
  "../node_modules/bootstrap/dist/css/bootstrap.min.css",
  "../node_modules/ngx-bootstrap/datepicker/bs-datepicker.css",
  "styles.css"
]

At this point when you view the page in Google chrome or Firefox, you get the same datepicker and hence the same experience.
angular datepicker tutorial

When we select a date from the date-picker control, the "Date of Birth" textbox is automatically populated with the selected date and it is also captured by the angular generated form model.

With this datepicker control, it is also very easy to capture a date range. For example, you have an open job role, and you want to capture a date range for accepting CV's, we can very easily do this. All we have to do is use bsDaterangepicker directive instead of bsDatepicker directive on the input element as shown below.

<div class="form-group">
  <label for="dateOfBirth">Date of Birth</label>
  <input id="dateOfBirth" name="dateOfBirth" [(ngModel)]="dateOfBirth"
          type="text" bsDaterangepicker class="form-control" />

</div>

The above simple change, will display Daterange picker as shown below. When we select a date range, the corresponding input field is automatically populated with the selected date range and it is also captured by the angular generated form model.
angular date range picker
  • At the moment, the Datepicker is using the default green theme. We want to change it to dark-blue theme, so it matches with the rest of the form.
  • The date is captured in the textbox in mm/dd/yyyy format. We want to change it to dd/mm/yyyy format
  • At the moment there is no default date. We want to set a default date
  • The input element is spanning across the entire width of the form. We want to limit it's width
Datepicker is a highly configurable component. We will discuss how to do all of the above in our next video.

angular crud tutorial

21 comments:

  1. hi venkat, your videos are good, i' m getting this error while i want to implement bootstrap@4 version


    could you please letme know how to solve this problem ???


    ERROR in ./node_modules/css-loader?{"sourceMap":false,"importLoaders":1}!./node_modules/postcss-loader/lib?{"ident":"postcss","sourceMap":false}!./node_modules/sass-loader/lib/loader.js?{"sourceMap":false,"precision":8,"includePaths":[]}!./node_modules/bootstrap/scss/bootstrap.scss Module build failed: BrowserslistError: Unknown browser major at error (E:*********\node_modules\browserslist\index.js:37:11) at Function.browserslist.checkName (E:*********\node_modules\browserslist\index.js:320:18) at Function.select (E:*********\node_modules\browserslist\index.js:438:37) at E:*********\node_modules\browserslist\index.js:207:41 at Array.forEach () at browserslist (E:*********\node_modules\browserslist\index.js:196:13) at Browsers.parse (E:*********\node_modules\autoprefixer\lib\browsers.js:44:14) at new Browsers (E:*********\node_modules\autoprefixer\lib\browsers.js:39:28) at loadPrefixes (E:*********\node_modules\autoprefixer\lib\autoprefixer.js:56:18) at plugin (E:*********\node_modules\autoprefixer\lib\autoprefixer.js:62:18) at LazyResult.run (E:*********\node_modules\postcss-loader\node_modules\postcss\lib\lazy-result.js:270:20) at LazyResult.asyncTick (E:*********\node_modules\postcss-loader\node_modules\postcss\lib\lazy-result.js:185:32) at LazyResult.asyncTick (E:*********\node_modules\postcss-loader\node_modules\postcss\lib\lazy-result.js:197:22) at LazyResult.asyncTick (E:*********\node_modules\postcss-loader\node_modules\postcss\lib\lazy-result.js:197:22) at processing.Promise.then._this2.processed (E:*********\node_modules\postcss-loader\node_modules\postcss\lib\lazy-result.js:224:20) at new Promise () @ ./node_modules/bootstrap/scss/bootstrap.scss 4:14-164 @ multi ./node_modules/bootstrap/scss/bootstrap.scss ./node_modules/font-awesome/scss/font-awesome.scss ./node_modules/ng2-toastr/bundles/ng2-toastr.min.css ./node_modules/owl.carousel/dist/assets/owl.carousel.css ./node_modules/owl.carousel/dist/assets/owl.theme.default.css ./node_modules/froala-editor/css/froala_editor.pkgd.min.css ./node_modules/froala-editor/css/froala_style.min.css ./node_modules/ng-pick-datetime/assets/style/picker.min.css ./src/styles.scss

    ReplyDelete
  2. i got same error but i resolved using npm uninstall bootstrap@4 --save

    then again npm install@3 --save

    if anyone find to implement bootstrap 4 let me know

    ReplyDelete
  3. Cannot read property 'schedule' of undefined issue

    ReplyDelete
  4. BsDatepickerModule is under development,
    BREAKING CHANGES are possible,
    PLEASE, read changelog

    Firstly, above warning messages shows
    and then, when i clicked into the textbox it gives below error
    BsDatepickerContainerComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'schedule' of undefined
    at ObserveOnSubscriber.scheduleMessage (observeOn.js:99)
    at ObserveOnSubscriber._error (observeOn.js:105)
    at ObserveOnSubscriber.Subscriber.error (Subscriber.js:108)
    at BehaviorSubject.Observable._trySubscribe (Observable.js:177)
    at BehaviorSubject.Subject._trySubscribe (Subject.js:97)
    at BehaviorSubject.Observable.subscribe (Observable.js:160)
    at ObserveOnOperator.call (observeOn.js:74)
    at AnonymousSubject.Observable.subscribe (Observable.js:157)
    at ScanOperator.call (scan.js:72)
    at AnonymousSubject.Observable.subscribe (Observable.js:157)

    ReplyDelete
  5. how to validate in angular 4 datepicker ?

    ReplyDelete
  6. Hello venkat,
    i got bellow error
    ERROR typeError: Ubable to get property 'schedule' of undefined or null reference
    kindly help me

    ReplyDelete
  7. Hi,

    I am Getting Billow Error while implementing this DatePicker

    ERROR TypeError: "this.scheduler is undefined"
    scheduleMessagewebpack-internal:///../../../../rxjs/_esm5/operators/observeOn.js:105:9_errorwebpack-internal:///../../../../rxjs/_esm5/operators/observeOn.js:111:9errorwebpack-internal:///../../../../rxjs/_esm5/Subscriber.js:110:13_trySubscribewebpack-internal:///../../../../rxjs/Observable.js:177:13_trySubscribewebpack-internal:///../../../../rxjs/Subject.js:97:20subscribewebpack-internal:///../../../../rxjs/Observable.js:160:88callwebpack-internal:///../../../../rxjs/_esm5/operators/observeOn.js:80:16

    ReplyDelete
  8. Hi Venkat,encountered below prob when installed ngx-bootstrap. My bootstrap version is 3.3.7.
    npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}

    ReplyDelete
  9. use command for bootstrap 4: npm install npm install bootstrap@3.3.7 --save

    ReplyDelete
  10. there is no error in shown but datepicker is not working means not shown any date picker only textbox is shown

    ReplyDelete
    Replies




    1. I am facing same error but when i use proper order in app module it work for me
      imports: [
      BrowserModule,FormsModule,
      BsDatepickerModule.forRoot(),
      RouterModule.forRoot(appRoutes),
      AppRoutingModule,
      ],

      Delete
  11. Hi kudvenkat sir, can u help me on this when i am selecting the date from date-picker control loses it's focus so how cab handle this problem

    ReplyDelete
  12. Hi Venkat,

    Thanks for the wonderful video. I have got some error, when implement date picker please help.

    Error Below :

    ERROR in node_modules/ngx-bootstrap/chronos/utils/type-checks.d.ts(8,62): error TS2304: Cannot find name 'Extract'.

    node_modules/ngx-bootstrap/datepicker/reducer/bs-datepicker.actions.d.ts(5,33): error TS1039: Initializers are not allowed in ambient contexts.

    Thanks

    ReplyDelete
  13. i got error. it's gone after I add this is appModul
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

    ReplyDelete
    Replies
    1. yes, it is working now, I added
      app.module.ts
      import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';
      import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

      imports: [
      BrowserModule,
      FormsModule,
      RouterModule.forRoot(appRoutes),
      BsDatepickerModule.forRoot(),
      BrowserAnimationsModule
      ],

      Delete
  14. Install below

    npm install --save @angular/animations

    @NgModule({
    bootstrap: [AppComponent],
    declarations: [AppComponent],
    imports: [BrowserModule, BrowserAnimationsModule]
    //
    })

    ReplyDelete
  15. npm install ngx-bootstrap@2.0.0-rc.0
    npm install bootstrap@3.3.7
    npm install -s rxjs-compat

    ReplyDelete
  16. I am using Angular 9 with bootstrap 4 and got the same animation error. issue resolved after
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

    ReplyDelete
  17. Need to import the below code in app.module.ts if using Angular 9 and above version

    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

    @NgModule({
    ...,
    imports: [
    ...,
    BrowserAnimationsModule
    ],
    ...
    })

    ReplyDelete

It would be great if you can help share these free resources