如何在 ngBootstrap 和 Angular 中监听模态的关闭事件?

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

我正在尝试使用 ngbootstra 订阅模式的关闭事件,但我不明白它是如何工作的。我有 2 个组件,第一个用于启动模态,第二个在内部。

第一名

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';
  }
}

第二个

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) { }
  

}

但我不知道如何进行订阅,因为它说 close 方法不是可观察的,而且我想知道如何在第二个组件中关闭模态时发出任何值 (2nd) Does有人知道怎么做吗?

顺便说一句,有必要取消订阅吗?

您可以访问 modalRefresult 变量,因为它 returns 是一个 Promise,即

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

有关详细信息,请参阅 documentation

你不能订阅 close 方法的原因是它 returns void 而不是 Observable(也在文档中列出)。

总的来说,我个人会将打开和关闭方法移动到服务中,以便您的其他组件(应该监听关闭事件的组件)可以访问 modalRef 变量。

其他组件

<button type="button" class="btn btn-outline-dark" (click)="close()">Close</button>
    
    
    close() {
        this.activeModal.close("Send data")
      }
    

所以你可以从父组件订阅这个

小丑组件

    open(): void{ 
        const modalRef = this.modalService.open(OtherComponent, {centered: true});
        modalRef.afterClosed().subscribe(data => {
              console.log(data)
              if(data){
                  // you can check if the modal returns any data or not
              }
        })
      }