Implementing Bootstrap Collapse in Angular: A Step-by-Step Guide
Learn how to integrate Bootstrap's collapse functionality into your Angular 8/9 applications using Ng Bootstrap. This tutorial provides a practical, step-by-step guide, covering installation, implementation, and usage of collapsible elements, enhancing your Angular projects with Bootstrap's responsive design features.
Implementing Bootstrap Collapse with Angular
This guide demonstrates how to use Bootstrap's collapse functionality within an Angular 9/8 application. We'll leverage Ng Bootstrap, a library that provides native Angular directives for Bootstrap components.
Steps to Implement Bootstrap Collapse in Angular
Follow these steps to add a collapsible element to your Angular project:
Step 1: Create a New Angular App
Use the Angular CLI to generate a new project:
ng new my-new-app
Step 2: Install Bootstrap 4
Install Bootstrap's core package using npm. This includes the Bootstrap CSS.
npm install bootstrap --save
Then, update your `angular.json` file to include the Bootstrap CSS file:
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"src/styles.css"
],
Step 3: Install Ng Bootstrap
Install Ng Bootstrap, which provides Angular directives for Bootstrap components:
npm install --save @ng-bootstrap/ng-bootstrap
Step 4: Import Ng Bootstrap Module
Import the Ng Bootstrap module into your `app.module.ts` file:
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
@NgModule({
imports: [
// ...other imports...
NgbModule
],
// ...rest of your module...
})
export class AppModule { }
Step 5: Update the View File (HTML)
Add the collapsible element to your component's HTML template (`app.component.html`):
<button type="button" class="btn btn-primary" (click)="isCollapsed = !isCollapsed" [attr.aria-expanded]="!isCollapsed">
Collapse Toggle
</button>
<div [ngbCollapse]="isCollapsed">
<div class="card">
<div class="card-body">
This content will collapse.
</div>
</div>
</div>
Step 6: Update the Component File (TypeScript)
In your component's TypeScript file (`app.component.ts`), manage the collapse state:
import { Component } from '@angular/core';
@Component({
// ...component metadata...
})
export class AppComponent {
isCollapsed = false;
}
Running the Application
Run your Angular application using:
ng serve