Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen the close event of a modal in ngBootstrap and Angular?

I'm trying to subscribe to the close event of a modal using ngbootstra, but I don't understand how it works. I have 2 components The 1st for lauching the modal and inside the 2nd one.

the 1st

html

<button class="btn btn-lg btn-outline-primary" (click)="open()">Launch demo modal</button>

TS

import { OtherComponent } from './../other/other.component';
import { Component, OnInit } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap/modal/modal.module';

@Component({
  selector: 'app-joker',
  templateUrl: './joker.component.html',
  styleUrls: ['./joker.component.scss']
})
export class JokerComponent {
  constructor(private modalService: NgbModal, private activeModal: NgbActiveModal) { }

  open(): void{ 
    const modalRef = this.modalService.open(OtherComponent, {centered: true});
    modalRef.componentInstance.name = 'Gerardo';
  }
}

The 2nd

html

<div class="modal-header">
  <h4 class="modal-title">Hi there!</h4>
  <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<div class="modal-body">
  <p>Hello, {{name}}!</p>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-outline-dark" (click)="activeModal.close('Close click')">Close</button>
</div>

TS

import { Component, Input} from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-other',
  templateUrl: './other.component.html',
  styleUrls: ['./other.component.scss']
})
export class OtherComponent {

  @Input() name: any;
  constructor(public activeModal: NgbActiveModal) { }
  

}

But I don't know hoy to do the subscribe because it says that the close method is not an observable, also I like know how to emit any value when the modal is close in the 2nd component (2nd) Does some know how to do it?.

Btw is it necessary to do a unsubscribe?

like image 855
geraktOfRivia Avatar asked Oct 18 '25 05:10

geraktOfRivia


1 Answers

You can access the result variable of your modalRef, as it returns a Promise, ie

modalRef.result.then((data) => {
  // on close
},
(error) => {
  // on error/dismiss
});

See the documentation for further information.

And the reason you cannot subscribe to the close method is that it returns void instead of an Observable (listed in the docs as well).

On a general note, personally I'd move the open and close methods to a service so your other component (the one supposed to be listening to the close event) can access the modalRef variable.

like image 133
Aldin Bradaric Avatar answered Oct 19 '25 17:10

Aldin Bradaric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!