Angular modal not progressing past initial message due to Bootstrap integration issue

The modal functionality only seems to be working for the first message I send, as subsequent messages do not appear.

My environment includes: Angular 17 Bootstrap 5.3

This is the TypeScript file snippet:

import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UserService } from '../../services/user/user.service';
import { iUserDTO } from '../../models/iUserDTO';
import * as bootstrap from 'bootstrap';

// Rest of the TypeScript code here...

Below is the HTML code where the issue persists with the close button appearing in the footer section:

<!-- users-add.component.html -->
<div class="container users-add">
  <form [formGroup]="myForm" (ngSubmit)="onSubmit()">
    <!-- Form fields and structure here -->
  </form>
</div>

<!-- Modal Section -->
<div class="modal fade" id="errorModal" tabindex="-1" aria-labelledby="errorModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <!-- Modal header, body, and footer details here -->
    </div>
  </div>
</div>

Despite troubleshooting my logic thoroughly, it appears that there might be a bug or inconsistency within Bootstrap causing this malfunction.

I have attempted various methods like resetting the form, clearing modal messages, and using dispose but haven't resolved the issue.

Interestingly, errors are correctly displayed when using existing data, yet if the data is altered, the modal gets stuck and shows the initial error message.

Answer №1

Ensure to initialize the modal only once, manage event listeners for form reset, and use bind listener context for better functionality. Here is an example of how you can achieve this:

private modal: bootstrap.Modal | null = null;
private modalElement: HTMLElement | null = null;

constructor(){
    //...
    // Add this at the end of constructor
    this.modalElement = document.getElementById('errorModal');
    if (this.modalElement) {
        this.modal = new bootstrap.Modal(this.modalElement);
    }
}

// Updated showModal method:
private showModal(message: string, header: string): void {
    this.modalMessage = message;
    this.modalHeader = header;

    if (this.modal && this.modalElement) {
        this.modal.show();

        // Remove existing event listeners before adding a new one
        this.modalElement.removeEventListener('hidden.bs.modal', this.resetFormListener);

        // Attach event listener to reset form on modal close
        this.modalElement.addEventListener('hidden.bs.modal', this.resetFormListener.bind(this), { once: true });
    } else {
        console.error('Error: Modal element with id "errorModal" not found.');
    }
}

private resetFormListener(): void {
    if (this.modalHeader === 'Success') {
        this.resetForm();
    }
}

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

Post-Angular migration (going from version 12 to 14), there are still lingering security risks associated with the "d3-color vulnerable to ReDoS" issue

Following the migration to Angular 14, I made sure to update my "@swimlane/ngx-charts" version to "20.1.2" and the "d3" version to "7.8.4". However, even after running the npm install command, I am still encountering 5 high severity vulnerabilities in my p ...

A guide to sending data via POST in Angular2 using a service class

As I venture into developing a simple application form and posting data to the server, my Angular2 skills are being put to the test. I am particularly curious about how to smoothly transfer the data from the component to the service and eventually onto th ...

Strange behavior detected in TypeScript generic function when using a class as the generic parameter

class Class { } const f0 = <T extends typeof Class> (c:T): T => { return c } const call0 = f0 (Class) //ok const f1 = <T extends typeof Class> (c:T): T => { const a = new c() return a //TS2322: Type 'Class' is not assigna ...

Calculate the total sum of an array in Angular based on a specific condition of another key

How do I calculate the sum of array elements where sel1, sel2, or sel3 is equal to 1 from the following Array? [ { "sel1": 0, "sel2": 1, "sel3": 0, "price": 10 }, { "sel1": 0, "sel2": 1, &qu ...

An issue occurred while attempting to retrieve information from the database table

'// Encounter: Unable to retrieve data from the table. // My Code const sql = require('mssql/msnodesqlv8'); const poolPromise = new sql.ConnectionPool({ driver: 'msnodesqlv8', server: "test.database.windows.net", ...

The successful conversion of Typescript to a number is no longer effective

Just the other day, I was successfully converting strings to numbers with no issues. However, today things have taken a turn for the worse. Even after committing my changes thinking all was well, I now find that when attempting to cast in different ways, I ...

Creating a Protected Deployment Environment on AWS for Angular and Spring Boot Applications

Recently, I attempted to deploy a backend Spring Boot application and an Angular front end application on AWS. After successfully pushing my Docker image to ECS, I managed to run multiple services behind application load balancers. Specifically, I set up t ...

Getting unique identifiers for documents in AngularFire2's Firestore collections

After reviewing the Angularfirestores documentation, I found that it was not well documented. I encountered an issue while trying to retrieve unique IDs for each document from my Firestore database. Below is the code snippet I am working with: private bus ...

Error encountered when creating a new project using ASP.NET Core (.NET 5) and Angular 11

When I start a new ASP.NET Core Web API + Angular project in Visual Studio by using: dotnet new angular, it sets up a .NET 5 project with an Angular 8.2 project in the ClientApp folder. After hitting F5, everything runs smoothly. However, I want to work ...

When attempting to Dockerize an Angular CLI app, nothing seemed to happen

I attempted to dockerize my Angular application and created a Dockerfile as follows: FROM teracy/angular-cli as angular-built WORKDIR /usr/src/app COPY package.json package.json RUN npm install COPY . . RUN ng build FROM nginx:alpine LABEL author="pleijan ...

React - Component not updating after Axios call in separate file

Recently I decided to delve into React while working on some R&D projects. One of my goals was to build an application from scratch as a way to learn and practice with the framework. As I started working on my project, I encountered a rather perplexin ...

Ways to package object fields within an array

I am in possession of an object with various properties, ranging from arrays to objects. My goal is to transform the object so that each sub field is encapsulated within an array. For instance: "head": { "text": "Main title", "su ...

Discover the Location and Sign Up for Angular2+ Service

I'm currently using the Google Maps API to retrieve a user's geoLocation data, including latitude and longitude. My goal is to pass this information to a web API service in order to receive JSON output of surrounding addresses. I have implemented ...

Click to load additional data until the list has reached its full length

<ng-container *ngFor="let item of itemList | slice:0:3"> <mat-checkbox>{{item}}</mat-checkbox> </ng-container> <div> <button id="loadMore">Load More</button> </div> I wo ...

What could be causing the error within the 'react-code-blocks' library?

Currently, I am involved in a project that utilizes Typescript and React. However, I have encountered an issue while working with the 'react-code-blocks' library. The structure of my container component is as follows: interface ICodeBlockProps { ...

Filling out form controls with a variety of values

I'm currently working on a form that features multiple select dropdowns generated from data retrieved from an API. Although unsure if I'm approaching this correctly, I've managed to populate the form for the 'appointmentPackages' ...

New options for outdated Webpack i18n plugin and loader

I am currently working on a TypeScript project that requires loading translations from individual .json files assigned to each country. For instance, we would have separate language files like en.json, es.json. The goal is to be able to access these trans ...

Guide on navigating an array of objects using the provided keys as a starting point in Javascript/Typescript

Assuming I have an array of objects structured like this: const events: Array<{year: number, month: number, date: number}> = [ {year: 2020, month: 10, date: 13}, {year: 2021: month: 3, date: 12}, {year: 2021: month: 9, date: 6}, {year: 2021: mont ...

Guide to importing a class property from one file to another - Using Vue with Typescript

Here is the code from the src/middlewares/auth.ts file: import { Vue } from 'vue-property-decorator' export default class AuthGuard extends Vue { public guest(to: any, from: any, next: any): void { if (this.$store.state.authenticated) { ...

Utilizing the Loess npm module in conjunction with Angular 4

I am attempting to incorporate the Loess package into my project. The package can be found on NPM and offers various regression models for data fitting. I successfully installed it using npm install loess --save, and it now resides in the node_modules dire ...