Implementing Bootstrap 5 JS within an Angular 11 component TypeScript

I am currently working on a project that utilizes Angular 11 and we are aiming to integrate Bootstrap 5 native JS without relying on third-party libraries like ng-bootstrap, MDB, or ngx-bootstrap (jQuery is not being used as well). I understand that using JS libraries in TS may not be the best practice.

The main issue lies in how to import Bootstrap JS and utilize its objects and methods within Angular's TS components

Initially, my belief was that installing the following packages would suffice:

npm i bootstrap@next
npm i @types/bootstrap

Both packages have been successfully imported into package.json and are present in node_modules. Additionally, I included

"scripts": [ "node_modules/bootstrap/dist/js/bootstrap.js" ]
in angular.json, however, I still encounter difficulties utilizing them.

For instance, when attempting:

import { Carousel } from 'bootstrap';
...
carousel: Carousel | any;
...
this.carousel = document.getElementById('video-carousel')
this.carousel.interval = false;

In this case, where 'bootstrap' is sourced from '@types/Bootstrap'. The carousel should not cycle automatically, yet it does. This challenge persists with other types of Bootstrap elements as well.

Answer №1

I believe you may be utilizing the carousel element incorrectly. To properly utilize the carousel methods, you need to initialize a Carousel element with the appropriate configuration.

Instead of selecting the native HTML element that represents the carousel, it is recommended to create a new Carousel(elementRef, config) and make any necessary modifications by referencing 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 result in a carousel element that does not automatically slide.

For a practical example, you can check out this Stackblitz, where you can pause and play the carousel. Remember to import

node_modules/bootstrap/dist/js/bootstrap.js
in the scripts section of your angular.json file as well as
"./node_modules/bootstrap/dist/css/bootstrap.css"
in the styles.

Answer №2

The Carousel feature in Bootstrap relies on the use of Bootstrap's own JavaScript plugins and Popper.js. To ensure that your carousel functions properly, make sure to include popper.min.js before including Bootstrap’s JavaScript file. Alternatively, you can use bootstrap.bundle.min.js or bootstrap.bundle.js which already contain Popper and will resolve any issues. I faced a similar problem with the bootstrap dropdown-toggle not working. Instead of adding

"scripts": [ "node_modules/bootstrap/dist/js/bootstrap.js" ]
in the angular.json file, I included
"scripts": [ "node_modules/bootstrap/dist/js/bootstrap.bundle.min.js" ]
(with Popper included) which solved the problem effortlessly.

Answer №3

Even if you include

node_modules/bootstrap/dist/js/bootstrap.js
in your angular.json, your component may not recognize it properly. It is better to only add the necessary code in your component to enable tree shaking.

To utilize Bootstrap functionality, such as modals, in your component, import the specific bootstrap js file like this:

import Bootstrap from 'bootstrap/dist/js/bootstrap';

Create a variable for the bootstrap modal and use @ViewChild as shown below:

modalDirect: Bootstrap.Modal;
@ViewChild('demoModal') input;
Now, create a method to open the Bootstrap 5 modal when a button is clicked
open(element): void {
  this.modalDirect = new Bootstrap.Modal(element, {});
}

Now it should be functioning correctly.

For an example, you can visit

https://github.com/aniruddhadas9/bootstrap5-angular10-without-JQuery/blob/master/src/app/components/home/home.component.ts

Answer №4

After encountering a similar issue, I discovered that the problem was due to incorrectly importing scripts and styles in the wrong location. It's crucial to ensure that you're importing them within the correct area.

"architect": { 
  "build": {
    "options": {
       ...
     "styles": [],
     "scripts": []
     }
  }
}

In my case, I mistakenly imported mine inside "test": { .... }.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript: The type 'Observable<{}>' cannot be assigned to the type 'Observable'

I'm encountering an issue with the Observable type, any thoughts on how to resolve it? import { PostModel } from '../model/postModel'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable&ap ...

NodeJs and React do not automatically refresh files when using https protocol

I'm facing a frustrating issue that I just can't seem to crack... No matter what I try, I can't figure out why when I access the application through IP:3000, it loads updated files perfectly fine. But when I try to access it via , it refuse ...

Pop-up window for uploading files

Looking for assistance with my file uploading system. I am utilizing a unique purple button from http://tympanus.net/Development/CreativeButtons/ (Scroll down to find the purple buttons). Additionally, I am using a wide, short content popup feature availa ...

Steps to prevent closing the alert box when clicking outside of it in Ionic

I am currently developing an Ionic 2 app and I have implemented the following component: http://ionicframework.com/docs/components/#alert import { AlertController } from 'ionic-angular'; export class MyPage { constructor(public alertCtrl: Al ...

Wait for the response from a post request in Angular and retrieve the value once it becomes accessible

In my current method, I am sending data to the backend and receiving information about any mutations that occurred (specifically, how many new rows were added to the database). However, when using this method in its current state, the response holds the de ...

Issue with Django and Angular 4 - The requested resource is missing the 'Access-Control-Allow-Origin' header

This is my django code snippet Whenever I test my delete function, this error occurs: The requested resource does not include the 'Access-Control-Allow-Origin' header. This means that the origin is not permitted access. The response resulted ...

The improved approach to implementing guards in Angular

I am currently looking for the most effective way to utilize Angular "guards" to determine if a user is logged in. Currently, I am checking if the token is stored. However, I am wondering if it would be better to create an endpoint in my API that can verif ...

Error in Nuxt build due to missing core-js dependencies in ./node_modules/bootstrap-vue/:variouspath

After working on my nuxt.js project, I encountered some less-than-friendly error messages. Despite performing a clean install by deleting package.lock and node_modules, as well as installing core-js@2 and @babel/runtime-corejs2, the errors persist. ERR ...

What is the best way to integrate Angular types (excluding JS) into tsconfig to avoid the need for importing them constantly?

Lately, I've been dedicated to finding a solution for incorporating Angular types directly into my .d.ts files without the need to import them elsewhere. Initially, I attempted to install @types/angular, only to realize it was meant for AngularJS, whi ...

Guide to making a second request using an if statement inside an observable

The aim I have a requirement to make two HTTP requests. The first request should always be executed, and the second request should only be made if a certain condition is met. A signal needs to be emitted when: firstvar and secondvar are equal, and only ...

The application is experiencing extended loading times during production

After deploying my Angular 2 app on Heroku, I've noticed that it's taking a long time to load. Is there a way to bundle everything up instead of having all the scripts and stylesheets scattered across my index.html file? <html> <head> ...

Testing the speed of the client's side

In my quest to create an application that allows users to conduct a speedtest on their WiFi network, I have encountered some challenges. While standalone speedtest apps like Speedtest.net and Google exist, server-based speed test modules from NPM are not s ...

Avoiding Re-renders in an Angular2 Countdown Component

I am facing an issue with my Angular2 master component that includes multiple child components and a standalone countdown component called "clock". The countdown component updates its label every second, causing unnecessary re-rendering of the master compo ...

When the first argument is missing, using a recursive constraint default can result in the incorrect inference of the second argument, especially when both arguments share the same generic

Currently, I am developing a TypeScript implementation of a recursive binary search tree (BST) data structure using generic constraints. In order to establish a default for the recursive generic variable T without directly using it in the default declarati ...

Setting up npm, gulp, and bower on a shared Debian development environment for multiple users

I am managing a development server (running on debian) that is utilized by multiple developers, each having their own user profile with SSH access and vhost configuration. I would like to enable them to easily use npm install, gulp, and bower for their re ...

Encountering difficulty retrieving host component within a directive while working with Angular 12

After upgrading our project from Angular 8 to Angular 12, I've been facing an issue with accessing the host component reference in the directive. Here is the original Angular 8 directive code: export class CardNumberMaskingDirective implements OnInit ...

How to Access node_module in SailsJS View

I am currently working on a small project using sails(). Following the documentation has been smooth so far, but as someone new to JavaScript frameworks and npm, I have run into some difficulties when trying to include other node_modules in my .ejs views ...

I'm having trouble with npm run dev. It keeps saying that the command `hydrogen dev` is

Running 'npm run dev' results in the following message. ? Command `hydrogen dev` not recognized. Did you mean `kitchen-sink prompts`? > (y) Yes, confirm (n) No, cancel Press ↑↓ arrows to choose, enter or a shortcut to confirm. c ...

Progressive File Upload in ASP.NET Core 2.0 and Angular 4.3: A Seamless Integration

Is there a way to utilize the latest Angular 4.3 HttpClient to handle file uploads and retrieval in an ASP.NET Core 2.0 Controller, all while providing live upload progress updates to the client? ...

Error: The file type you are trying to upload is not supported

my document-upload.service.ts private uploadFile(file: File) { let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new HttpHeaders({'Content-Type': 'multip ...