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

标签 angular typescript ng-bootstrap angular2-observables

我正在尝试使用 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 方法不是可观察的,我也想知道如何在第二个组件中关闭模态时发出任何值(第二)有人知道吗怎么做?

顺便说一下,是否有必要取消订阅?

最佳答案

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

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

参见 documentation了解更多信息。

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

一般而言,我个人会将打开和关闭方法移至服务,以便您的其他组件(应该监听关闭事件的组件)可以访问 modalRef 变量。

关于angular - 如何在 ngBootstrap 和 Angular 中监听模态的关闭事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65101495/

相关文章:

Angular2 ngSwitch 不工作

javascript - Typescript 和 Javascript ES6、ES.NEXT 类构造函数参数对比

angular - 为什么我在 Angular 10 中安装 ng-bootstrap 后立即出现构建错误?

angular - 将 ng-template 放在 *ngFor 中会影响性能吗?

angular - 从延迟加载的模块打开模式

angular - 如何在失去焦点时保持 Material 选择列表突出显示?

Angular2向路由器url添加参数

typescript - 获取路由查询参数

javascript - 使用 Typescript 强制接口(interface)的通用约束?

typescript - Firebase 功能与 typescript 和身份验证