A guide on incorporating Bootstrap 5 modal into an Angular project

I have added bootstrap 5 to my index.html file

<link href="assets/css/bootstrap.min.css" rel="stylesheet" media="screen">

I attempted to implement the code from Bootstrap documentation on my Angular page, but it's not functioning correctly.

Any ideas on why it's not working? Is there an alternative method to use modals in an Angular page?

Answer №1

If you're looking to make things run smoothly in the year 2021, follow these steps:

Start by installing Bootstrap using the command npm install --save bootstrap

Next, in your angular.json file, ensure you set the proper routes for Bootstrap's CSS and JS files

Then, in your component.ts file, include the following code:

import * as bootstrap from 'bootstrap';

  modalName: bootstrap.Modal | undefined
save(){
    this.testModal?.toggle()
  }
  openModal(element){
    this.testModal = new bootstrap.Modal(element,{} ) 
    this.testModal?.show()
  }

Finally, in your component.html file, add the following code:

<button class="btn btn-primary" (click)="openModal(testModal)">Add dish</button>
    
<div class="modal" tabindex="-1" #testModal id="testModal"> ...</div>

Answer №3

Execute the following commands in our project terminal to install Bootstrap 5 modules into our Angular application:

npm install bootstrap@next

Insert the code below into the src/app/app.component.html file to see the final output on the web browser:

  <!-- Button trigger modal -->
   <button type="button" class="btn btn-primary" data-bs-toggle="modal" 
  data-bs-target="#exampleModal">
  Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria- 
  labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title text-danger" id="exampleModalLabel">Hey 
      Bootstrap 5!!</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" 
       aria-label="Close"></button>
      </div>
      <div class="modal-body text-danger">
       Therichpost.com
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-warning" data-bs- 
       dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

The following code needs to be added to the angular.json file:

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

Answer №4

let modalInstance = new (window as any).bootstrap.Modal(element);
//modalInstance.toggle();
//modalInstance.show();
//modalInstance.hide();
//modalInstance.dispose();

Answer №5

After experimenting with various solutions, I finally found success with the helpful advice from @Gajanan. I am sharing this for my future self or anyone else who may come across the same issue. It's actually quite simple and could be easily found in either the Bootstrap documentation or the Angular documentation.

Here is the step-by-step process I followed:

  1. Started a new Angular project from the cli, using scss and TypeScript.
  2. Downloaded Bootstrap using NPM.
  3. Added the Bootstrap .scss file to the default styles scss.

Initially, everything seemed fine as the Bootstrap styles loaded correctly. However, when I tried to use the modal, it didn't work as expected. Thanks to @Gajanan's solution, I was able to resolve the issue.

One additional tip to keep in mind is to ensure that you add the script in the correct location. I made the mistake of adding it elsewhere, wasting about 15 minutes in the process.

{
  ...
  "projects": {
    ...
    "myProject": {
      ...
      "architect": {
        ...
        "build": {
          ...
          "options": {
            ...
            "scripts": ["here 🎉"],
          },
          ...
          "test": {
            ...
            "options": {
              ...
              "scripts": ["NOT here"],
            }
          }
        }
      }
    }
  }
}

I know it may seem obvious, but I learned my lesson the hard way. Consider this my way of reminding myself not to make that mistake again.

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

Combining all CSS files into one and consolidating all JavaScript files into a single unified file

Whenever I need to add a new CSS or JS file, I always place it in the header section like this Add CSS files <link rel="stylesheet" href="<?php echo URL; ?>public/css/header.css" /> <link rel="stylesheet" href="<?php echo URL; ?> ...

Setting up aliases for "HTML import" paths - a step-by-step guide

Recently, I've been experimenting with Web Components and Polymer, creating a basic single-page application. Within my project, I have various custom components. My HTML imports are structured like this: <link rel="import" href="../core-icon/core ...

Strategies for aligning tooltips with the locations of dragged elements

One of my projects involves a simple drag element example inspired by Angular documentation. The example features a button that can be dragged around within a container and comes with a tooltip. <div class="example-boundary"> <div ...

When the mouse hovers over the slider, the final image jumps into view

After successfully building an image slider that displays 2 partial images and 1 full image on hover, I encountered a bug when setting the last image to its full width by default. This caused a temporary gap in the slider as the other images were hovered o ...

Steps to incorporate Ajax into current pagination system built with PHP and Mysql

Greetings! I am a beginner programmer looking to enhance my PHP & Mysql based pagination with Ajax functionality. Despite searching through numerous tutorials, I have been unsuccessful in finding a guide that explains how to integrate Ajax into existin ...

Angular: Concealing a Component within a Controller

Being new to Angular, I am trying to figure out how to programmatically hide/show a component using the controller. I am having trouble understanding how to access my component and set ng-hide to false. Currently, my controller includes a service call. Af ...

Why is it that this particular line of code sometimes gives me an "undefined" result before returning an actual value?

Why does the method 'equal' always return with an "undefined" followed by a number? And when I try to parse it, it returns me a NaN. <!DOCTYPE> <html> <head> <script> var fnum = 0; var secondNum; var operation; functi ...

What is the best way to organize inputs in a column? I have included a reference below to show my desired layout

<mat-form-field appearance="standard"> <mat-label>Full Name *</mat-label> <input matInput [(ngModel)]="currentUser.fullName"> </mat-form-field> <mat-form-field appearance="standard"&g ...

A guide to activating automatic filling of usernames and passwords in web browsers

On my login page, I aim to make the user experience seamless by automatically filling in the username and password fields once a user has logged in for the first time. This way, when they return to the login page, all they have to do is click the login but ...

What might be the reason why the custom markers on the HERE map are not displaying in Angular?

I'm having trouble displaying custom icons on HERE maps. Despite not receiving any errors, the icons are not showing up as expected. I have created a demo at the following link for reference: https://stackblitz.com/edit/angular-ivy-zp8fy5?file=src%2Fa ...

The functionality of images and links is compromised when they are assigned as values to properties within a JSON object

My images and links are not working, even after declaring them globally. When I write the src directly into src, everything seems fine but the alert pops up with the same URL and img src. Can anyone help? var combo0; var combo1; var combo2; var combo3; ...

Using div tags may cause rendering issues

I am trying to use multiple div tags with webkit borders, but for some reason only the one called 'Wrapper' is displaying properly. Here is my code: .wrapper { margin: 20px auto 20px auto; width: 800px; background: url('images/background_1. ...

The hamburger menu unexpectedly appears outside the visible screen area and then reappears at random intervals

My website has a hamburger menu for mobile devices, but there's a problem. When the page loads on a small screen, the hamburger menu is off to the right, causing side scrolling issues and white space. I thought it might be a CSS problem, but after exp ...

Creating column gaps that remain consistent when resizing a webpage is essential for maintaining a clean and organized layout

Visit my current site [This is the HTML code for my website:][2] <div class="column-box" style="width: 100%"></div> <div id="column1" style="float:left; margin:15; width:33%;"> <p>Sara Adams<br> I am a Web Developer and C ...

What could be causing the "Error: InvalidPipeArgument" to appear in my Angular code?

Currently, I am tackling a challenge within my Angular project that involves the following situation: Essentially, my HomeComponent view code looks like this: <div class="courses-panel"> <h3>All Courses</h3> <mat-t ...

Sonarqube coverage report is missing in Gitlab CI, but it works fine when running locally

I have encountered an issue with my Angular application deployed via GitLab CI. The deployment to the hosted Sonarqube instance is successful, but none of the code coverage reports are appearing unfortunately. Below is my GitLab yml file: stages: - te ...

unable to toggle the navbar

Currently, I am facing an issue with the navbar-toggle button while using Bootstrap. Initially, I thought the problem was with my navbar code, so I tried pasting the example from the Bootstrap Website, but it did not work either. The button appears, but t ...

Unable to adjust iframe height

Below is a snippet of code that I am working with: <style type="text/css"> .div_class { position:absolute; border:1px solid blue; left:50%; margin-left:-375px; margin-top:100px; height:300px; width:500px; overflow:hidden; } .iframe_class { position: ...

The shadow effects and color overlays do not seem to be functioning properly in Mozilla Firefox

I have designed a popup registration form using the Bootstrap modal class. To ensure form validation, I have integrated some jQuery validation engine functionality. Additionally, I customized the appearance by adding a box shadow, adjusting the background ...

Tips for converting an entire column along the vertical axis to a different language

Looking for a solution with my grid view where I want to translate the items of the second column on the y axis, as shown in the image. I attempted to use the translateY() function, but it resulted in the need to scroll in order to see the translated items ...