Angular modal not responding to close event

My issue is that when I try to close a modal by pressing the X button, it doesn't work. Here is the button where I am triggering the modal:

<button type="submit" id="submit-form" class="btn btn-primary" (click)="openConfirmModal()">Restaurar</button>

In this case, the method openConfirmModal() is being called from my current component, which in turn triggers the modal from another service component called password-reset.service.ts:

import { PasswordResetService } from './password-reset.service';
export class PasswordResetComponent implements OnInit {
  modalRef: BsModalRef;
  
  constructor(private modalService: BsModalService,
   private passwordResetService: PasswordResetService) { }

  openConfirmModal() {
    this.passwordResetService.confirmar("HECHO", "Datos verificados! Por favor, revise su bandeja de entrada...").subscribe((answer) => {});
  }

This is the content of my password-service.ts:

import { ConfirmModalComponent } from './modals/confirm-modal/confirm-modal.component';
export class PasswordResetService {
  bsModalRef: BsModalRef;

  constructor(private bsModalService: BsModalService) { }

  public confirmar(title: string, message: string) : Observable<string> {
    const initialState = {
      title,
      message,
    };
    this.bsModalRef = this.bsModalService.show(ConfirmModalComponent, { initialState });
  
    return new Observable<string>(this.getModalSubscriber());
  }

  private getModalSubscriber() {
    return (observer) => {
        const subscription = this.bsModalService.onHidden.subscribe((reason: string) => {
            observer.complete()
        });

        return {
            unsubscribe() {
                subscription.unsubscribe();
            }
        }
    }
  }
}

Finally, this is the component that contains the modal and where I am attempting to trigger it:

confirm-modal.component.html:

<div class="modal-header">
    <h4 class="modal-title">{{title}}</h4>
    <button type="button" class="close pull-right" aria-label="Close" (click)="onClose()">
        <span aria-hidden="true"&>x</span>
    </button>
</div>
<div class="modal-body">
    <div class="message-margin">
      <p>{{message}}</p>
    </div>
</div>

confirm-modal.component:

export class ConfirmModalComponent implements OnInit {

  title: string;
  message: string;
  modalRef: BsModalRef;

  constructor(private modalService: BsModalService) { 
  }

  ngOnInit() {
  }

  onClose() {
    this.modalRef.hide();
  }
}

If anyone could assist me with this issue, I would greatly appreciate it. Thank you!

Answer №1

Change how the close modal event is triggered from a button to a span

<div class="modal-header">
    <h4 class="modal-title">{{title}}</h4>
    <button type="button" class="close pull-right" aria-label="Close">
        <span aria-hidden="true" (click)="onClose()">&times;</span>
    </button> </div> <div class="modal-body">
    <div class="message-margin">
      <p>{{message}}</p>
    </div> </div>

Answer №2

To handle the closing event in your getModalSubscriber function, listen for it and then invoke this.modalRef.hide() once the event is detected.

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

Accurately Showing Values of Observable Objects

Hey there, I'm diving deeper into Angular and working on my first project. I am fetching data from my database using a service method: getPost(postID: String) { this.postDocument = this.db.doc('posts/' + postID) return this.postDo ...

Issue encountered during the creation of a new Angular application (npm ERROR! 404 Not Found: @angular/animations@~7.1.0.)

I am currently using Windows 10, Node v11.0.0, and Angular CLI: 7.1.4. I encountered an error when trying to create a new Angular application. The error message is npm ERR! code E404 npm ERR! 404 Not Found: @angular/animations@~7.1.0. Error stack: 0 info ...

Guidelines on declining a pledge in NativeScript with Angular 2

I have encountered an issue with my code in Angular 2. It works fine in that framework, but when I tried using it in a Nativescript project, it failed to work properly. The problem arises when I attempt to reject a promise like this: login(credentials:Cr ...

Issue: FlashMessagesService not provided - NullInjectorError

Utilizing Angular 2 flash messages to showcase a message when the user clicks on the logout button has been quite the challenge. Despite adding a provider in navbar.component.ts and conducting various experiments, I still encounter the same error. Outline ...

forkJoin used in conjunction with switchMap fails to display expected results

One of the tasks I need to complete is to retrieve the MeasurementUnit for each ProductCategory by sending an API call for each ProductCategory. The issue arises in a specific service where the findAll function is subscribed to in a component, but the val ...

Updating the appearance of a non-declared HTML child component on-the-fly using Angular

Trying to dynamically adjust the style of an unspecified div is causing some trouble. Using Angular and PrimeNG, invisible divs are being generated that I cannot access through inline styles. The objective is to allow a user to input a width as a string (5 ...

Error in Angular multiselect dropdown: Unable to retrieve the length of undefined property

counter: number = 0; getDatatypes(){ if(this.counter == 0) { if(this.appId != 0) { if(undefined != this.datatypes && this.datatypes.length) for (let i = 0; i < this.datatypes.length; i++) { this.ap ...

I am searching for the vector geometric shapes svg elements that are commonly utilized in design editors. Can you point

When it comes to design editors, there are plenty of options such as Canva, Vistacreate, and Adobe Express. Each one uses a variety of styles for elements/objects/shapes. Are there any databases where I can find these resources? Some popular places include ...

Stop openapi-generator from altering enum names in JavaScript/TypeScript

We have implemented the openapi generator to create our REST client and it has been quite effective. However, we encountered an issue when using enums in the format UPERCASE_UNDERSCORE, as it ended up removing the underscores which caused inconvenience. Th ...

Tips for assigning an ID to a delete button when utilizing setValue in Angular 6

When we use setValue, how can we assign the ID of a row to the delete button? for (let i = 0; i < this.education.length; i++) { if (i !== 0) { const control = <FormArray>this.editEducation.controls['educationArray']; ...

Exploring the possibilities of ZMQ_XPUB_MANUAL in action with zeromq.js

I'm currently in the process of setting up a pub/sub broker using ZeroMQ, and I want to ensure that clients are only able to subscribe to authorized prefixes. While researching this topic, I came across a helpful tutorial that discusses achieving a si ...

Is Babel necessary for enabling JavaScript compatibility in my TypeScript React project, excluding Create React App?

This is the webpack configuration for my React project built in TypeScript, module.exports = { mode: 'development', entry: ['./src/main.tsx'], module: { rules: [ { // Rule for ts/tsx files only, no rule for js/js ...

Deactivating a Component in Ionic Angular

I am interested in including a CanDeactivate Guard in my Ionic Angular project. After reading about the new "CanDeactivateFn" Guard, I have been unable to find any information or examples on how to implement it. Could someone provide me with an example? ...

What is the best way to incorporate a background image using ngStyle?

I need help populating multiple cards in the following way: <mdl-card *ngFor="let product of templates" class="demo-card-event" mdl-shadow="2" [ngStyle]="{ 'background-color': 'lightgray' }"> <mdl-card-title mdl-card-expan ...

Passing an event between components in AngularDart

Two components, componentA and componentB, are siblings within the structure of componentMother. When componentA is clicked, an event is triggered and handled by event handlerA. How can this event be passed to componentB and handled by event handler B? W ...

Guide to Updating a Global Variable in Angular 2

I have been working with Angular 2 and I came across an issue with global variable access. To solve this, I created a service and injected it into my component pages. While I can access the variable in any page, updating it does not reflect the changes wh ...

Enriching SpriteWithDynamicBody with Phaser3 and Typescript

Is there a way to create a custom class hero that extends from SpriteWithDynamicBody? I'm unable to do so because SpriteWithDynamicBody is only defined as a type, and we can't extend from a type in Typescript. I can only extend from Sprite, but ...

Execute supplementary build scripts during the angular build process

I've developed an Angular application that loads an iframe containing a basic html page (iframe.html) and a Vanilla JavaScript file (iframe.js). To facilitate this, I've placed these 2 files in the assets folder so that they are automatically cop ...

What is the reason that TypeScript cannot replace a method of the base class with a subtype?

Here's a straightforward example. type Callback<T> = (sender: T) => void; class Warehouse<T> { private callbacks: Callback<T>[]; public constructor(callbacks: Callback<T>[]) { this.callbacks = callbacks; ...

"Troubleshooting: ngForm.controls returning undefined value in Angular application

Trying to test this HTML code in Angular: <form name="formCercarUsiari" #formCercarUsuari="ngForm" class="tab-content"> <input #inputNif class="form-control input-height" maxlength="100" type="text" placeholder="Indiqui NIF" name="nif" i18n-pla ...