Intercepting Bootstrap 4 modal display and conceal events using Typescript

While working on integrating a modal with the id myModal, I am attempting to connect it with events that trigger when it is shown and closed. I referred to the documentation at and implemented the following in my modal component:

this.modalElement = document.getElementById("myModal");
this.modalElement.addEventListener("hidden.bs.modal", this.onModalHidden);
this.modalElement.addEventListener("shown.bs.modal", this.onModalShown);

Currently, the event handlers are set up to simply log "shown" or "hidden" for testing purposes, but I am encountering difficulty getting it to function as intended:

private onModalShown = (event) => {
    console.log("modal is shown!!!");
}

I'm wondering if there might be something missing or if there's another way to achieve this?

Answer №1

If you want to receive notifications for the onOpen and onDismiss events within ModalComponent, you can easily subscribe to them.

@ViewChild('yourModal')
yourModal: ModalComponent;

To ensure proper event handling, I recommend subscribing to these events in the ngAfterViewInit lifecycle hook.

ngAfterViewInit() {
 this.yourModal.onOpen.subscribe(() => {
   //perform a specific action
 });

 this.yourModal.onDismiss.subscribe(() => {
   //perform another action
 });
}

Answer №2

Here are some code snippets you can try out:

To begin with, I utilized the ViewChild directive to access my modal.

    @ViewChild('MyModal') mymodal: ElementRef;

    //display
    $(this.mymodal.nativeElement).modal('show');
    //conceal
    $(this.mymodal.nativeElement).modal('hide');

    //capture the event when the modal is hidden
    //implicitly trigger hide when backdrop is clicked or ESC key pressed
    //I encountered issues with closing modals, and this resolved the problem
    $(this.mymodal.nativeElement).on('hidden.bs.modal',  () => {
        $(this).modal('hide');
        this.cancelProcedure();//my internal reset function
    });

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

How to achieve dynamic class instantiation through constructor injection in Angular 8?

Despite my efforts to find a solution, my understanding of Dependency Injection in services is still limited, making it challenging to get this thing working. I'm left wondering if there's any way to make it work at all. My current setup involve ...

Create a unique look for Angular components by customizing the hosting style

Is there a way to dynamically style the component host from within the component itself using the :host selector in a .css file? For instance, for a component like <app-test> </app-test>, I would like to be able to set the top property on the ...

Problems arise in React due to toaster interfering with spying on the 'useState' function

Having an issue with my notifications component while running tests using jest mock implementation on useState. Notifications.tsx import { Toaster } from "react-hot-toast"; export const Notifications = () => { return ( <Toaster ...

Troubleshooting Cross-Origin Resource Sharing (CORS) issue with Angular, Maven

I have been working on setting up an application with an Angular front-end and a Maven/Spring Boot backend. I've created my first REST controller, but when I attempt to send a GET HTTP request from my Angular IDE to the backend, I receive the followin ...

Unable to determine all parameters for Angular's DataService

I have been working on developing a versatile service and came across an informative article: https://medium.com/@krishna.acondy/a-generic-http-service-approach-for-angular-applications-a7bd8ff6a068 that guided me in creating my DataService. Here is a snip ...

Display JSON data in Angular view by extracting the desired value

Hey there! I have a GET response data with a field like "DeletionDate": "0001-01-01T00:00:00". What I'm trying to achieve is to remove the time part T00:00:00 and only display half of the value in my views. Is there a way to trim the value and show it ...

The combination of MUI pickers and date-fns led to a TypeError: the function utils.getYearText is not defined

In my latest project, I'm utilizing Material-UI V4, Material-UI Date/Time Pickers, and date-fns. The page design is minimalistic, and I have incorporated the DateTimePicker component from Material UI: <DateTimePicker label ...

What is a creative way to design a mat-radio-group without traditional radio buttons?

I am looking to create a component that offers users a list of selections with the ability to make only one choice at a time. The mat-radio-group functionality seems to be the best fit for this, but I prefer not to display the actual radio button next to t ...

Issue with React component not updating when the "Date" value in its state is changed

Disclaimer: I am currently working with React using Typescript. I have a particular component that, upon mounting, initializes state with a date like this: constructor(props: SomeProps) { super(props); const fromDate = new Date(); fromDat ...

Angular Material Slide-Toggle Takes Too Long to React

In my project, I am facing an issue with a control panel that contains an Angular Mat-Slide-Toggle element. Here is the code snippet: <mat-slide-toggle (change)="onQAStateDisplayChanged($event)">Display QA Status</mat-slide-toggle> When the c ...

What is the best way to create a scrollable horizontal element using bootstrap?

Here is the specific issue I'm facing: https://i.sstatic.net/oi94N.png The problem is that the icons are wrapping onto 2 lines, which is not the desired outcome. This is what I currently have: <li class="list-group-item participants-grouping-li" ...

404 Error: The requested API endpoint seems to have gone missing, as the URL cannot be found

I encountered a 404 not found error when attempting to create a new customer in my angular 10 application. Oddly, the API method works flawlessly in Postman but fails when called from the angular client. The cause of this issue is eluding me Using Postman ...

Troubles with the sliding feature on Bootstrap 4 Carousel

I'm encountering an issue with the bootstrap carousel as it's not sliding properly. Here is my current code: <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> ...

What's the best way to show a submenu when the main menu is scrollable?

I'm facing a challenge with the following issue: I am working with angular 8 and utilizing tieredMenu from primeng 8. The problem arises when I have a scroll, causing the tieredMenu's submenu to be hidden. Do you have any suggestions on how to ...

The custom css class is failing to be applied to a tooltip within Angular Material version 15

After updating Angular Material to version 15, I noticed that I can no longer apply custom coloring to the material tooltip. Here is an example code in .html: <button mat-raised-button matTooltip="Tooltip message" matTooltipClass="cu ...

Even with manual installation, the npm package still encounters dependency errors

Having trouble implementing the Imgur package from NPM into my Angular web app. The installation and import seemed to go smoothly, but when initializing a variable with the package, I encounter compile errors pointing to missing dependencies like 'cry ...

Unable to connect to 'highlight' as it is not a recognized attribute of 'code'

I have been experimenting with ngx-highlightjs and encountered an issue while trying to implement it in one of my module files. Due to having multiple modules, I am importing the HighlightModule only in the specific module where highlighting functionality ...

Do const generics similar to Rust exist in TypeScript?

Within TypeScript, literals are considered types. By implementing const-generics, I would have the ability to utilize the value of the literal within the type it belongs to. For example: class PreciseCurrency<const EXCHANGE_RATE: number> { amount ...

Should I include container-fluid in the body or main level for a Bootstrap 4 website?

When designing a Bootstrap 4 site, is it better to add container-fluid at the body or main level? For example: <html> <head></head> <body class= "container-fluid"> <header></header> <main></main> <footer ...

Tips for automatically assigning a default value in a material select within an Angular application

Currently, I have an Angular screen that displays data from a database using a Java REST API. There is a field called esValido which only contains values of 1 and 0 as shown in the initial image. https://i.sstatic.net/R4WCc.png My goal is to implement a ...