Integrating Bootstrap 4 Datepicker into Angular Applications with `ngx-bootstrap`

Learn how to seamlessly integrate Bootstrap 4's datepicker into your Angular projects using the `ngx-bootstrap` library. This tutorial provides a step-by-step guide, covering installation, configuration, and implementation for a user-friendly date selection experience.



Using Bootstrap Datepicker in Angular

Setting up the Angular Project

This guide demonstrates how to integrate Bootstrap 4's datepicker into an Angular application. We'll use the `ngx-bootstrap` library, which provides Angular components for Bootstrap UI elements. The process involves creating a new Angular project, installing necessary packages, importing modules, and updating the component's template and code.

Step 1: Create a New Angular App

Use the Angular CLI to create a new project:

Command

ng new my-new-app

Step 2: Install Bootstrap 4

Install Bootstrap's CSS using npm:

Command

npm install bootstrap --save

Then, update your `angular.json` file to include Bootstrap's CSS in your project's styles:

angular.json (Relevant Section)

"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css",
  "src/styles.css"
],

Step 3: Install ngx-bootstrap

Install the `ngx-bootstrap` library, which provides Angular directives for Bootstrap components:

Command

npm install --save @ng-bootstrap/ng-bootstrap

Step 4: Import Modules

Import the necessary modules (`NgbModule` and `FormsModule`) into your `app.module.ts` file:

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    NgbModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 5: Update the View (app.component.html)

Add an input field for the datepicker to your component's template (e.g., `app.component.html`):

app.component.html

<input type="text" class="form-control" name="dp" ngbDatepicker #dp="ngbDatepicker" [(ngModel)]="model">

Step 6: Update the Component (app.component.ts)

Update your component's TypeScript file (e.g., `app.component.ts`) to handle the datepicker model.

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'appBootstrap';
  model;
}

After completing these steps, run `ng serve` to start the development server. The datepicker should be integrated into your application.