Bootstrap is a popular CSS framework that provides a set of ready-to-use components and styles for building responsive web applications. In this article, we will explore how to enable Bootstrap Tooltip in an Angular application using an attribute directive.
Install Bootstrap:
npm install bootstrap
Import Bootstrap SCSS in styles.scss
:
// For Setting Project Specific Bootstrap Variable. Like $primary Color
@import "assets/scss/variables.scss";
// Import Bootstrap
@import "../node_modules/bootstrap/scss/bootstrap.scss";
// App Specific components
@import "assets/scss/app.scss";
Import Bootstrap Bundle JS in angular.json -> architect -> build -> options
:
"scripts": [
"node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
]
Add bootstrap
as a global variable in src/typings.d.ts
declare var bootstrap: any;
Now create a Directive TooltipDirective
:
src/app/_components/tooltip.directive.ts:
import { AfterViewInit, Directive, ElementRef, OnDestroy } from '@angular/core';
@Directive({
selector: '[bTooltip]'
})
export class TooltipDirective implements AfterViewInit, OnDestroy {
private tooltip: any;
constructor(private elementRef: ElementRef) {}
ngAfterViewInit() {
const domElement: HTMLElement = this.elementRef.nativeElement;
this.tooltip = new bootstrap.Tooltip(domElement);
}
ngOnDestroy(): void {
this.tooltip.dispose();
}
}
src/app/_components/tooltip.directive.spec.ts
import { ElementRef } from '@angular/core';
import { TooltipDirective } from './tooltip.directive';
describe('TooltipDirective', () => {
it('should create an instance', () => {
const elementRefMock: ElementRef = {} as ElementRef;
const directive = new TooltipDirective(elementRefMock);
expect(directive).toBeTruthy();
});
});
Declare Tooltip directive in src/app/app.module.ts
:
import { TooltipDirective } from './_components/tooltip.directive';
@NgModule({
declarations: [
...
TooltipDirective
]
})
Use the directive as below to create a tooltip:
<a class="btn btn-success" bTooltip title="Your Message">MyButton</a>
Now you will be able to use Tooltip with all it's attributes like data-bs-placement
.
I think with similar approach you can use most of the Bootstrap components in Angular.
Leave a Reply