I'm working on a project that uses Angular 11, we want to use Bootstrap 5 native JS, without third parties like ng-bootstrap, MDB, or ngx-bootstrap (We are not using jQuery as well). I know using JS libraries on TS is not ideal.
The problem is how to import Bootstrap JS and use its objects and methods in Angular's TS components.
Initially I thought installing the following packages would be enough:
npm i bootstrap@next
npm i @types/bootstrap
Both have been imported in the package.json
and are available in node_modules
. I've also imported "scripts": [ "node_modules/bootstrap/dist/js/bootstrap.js" ]
inside of angular.json
, but I still cannot use them.
For example, if I do:
import { Carousel } from 'bootstrap';
...
carousel: Carousel | any;
...
this.carousel = document.getElementById('video-carousel')
this.carousel.interval = false;
Where 'bootstrap'
is '@types/Bootstrap'
. The carousel shouldn't cycle automatically, but it does. This happens with every other Bootstrap type.
I think that you are using the carousel element in a bit wrong way. In order to use the carousel methods you should initialize a Carousel
element with the appropriate config.
Instead selecting the native HTML element that represents the carousel you should create new Carousel(elementRef, config)
and make any further changes by referring the class.
<div #carouselExampleSlidesOnly class="carousel slide">
<div class="carousel-inner">
<div class="carousel-item red active">
Text 1
</div>
<div class="carousel-item orange">
Text 2
</div>
<div class="carousel-item blue">
Text 3
</div>
</div>
</div>
...
@ViewChild("carouselExampleSlidesOnly") carouselElement: ElementRef<
HTMLElement
>;
carouselRef: Carousel;
...
ngAfterViewInit() {
this.carouselRef = new Carousel(this.carouselElement.nativeElement, {
slide: false
});
}
...
This will create a carousel element that doesn't auto slide.
Here is a working Stackblitz example, where you can pause and play the carousel, keep in mind that beside importing the node_modules/bootstrap/dist/js/bootstrap.js
in the scripts
inside your angular.json
you should also import "./node_modules/bootstrap/dist/css/bootstrap.css"
in the styles
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With