如何在打开的模态组件中访问“BsModalRef”?

How to get access to `BsModalRef` in opened modal component?

我是 Angular 的新手 4.I 一直在研究 Angular 1.5.x,现在正在 Angular 4 中转换相同的应用程序ngUpgrade 混合方法。 我在我的混合应用程序中使用 ngx-bootstrap 模态组件来替换现有的模态服务。

我在遵循指南时发现了一些问题 ngx-bootstrap-modal with service

这个语句有问题If you passed a component to .show() you can get access to opened modal by injecting BsModalRef

我在这里复制相同的例子,

export class ModalContentComponent {
  public title: string;
  public list: any[] = [];
  constructor(public bsModalRef: BsModalRef) {}  // How do you get bsModalRef here
}

我尝试 运行 这个例子,但我从来没有在打开的模式中得到 bsModalRef

我也尝试将 bsModalRef 传递给 content,但它适用于一种模态,而无法使用嵌套模态。

还有其他方法可以在 ModalContentComponent 中传递 bsModalRef 吗?

在这里找到完整的例子,

import { Component } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';

@Component({
 selector: 'demo-modal-service-component',
 templateUrl: './service-component.html'
})
export class DemoModalServiceFromComponent {
 bsModalRef: BsModalRef;
constructor(private modalService: BsModalService) {}

public openModalWithComponent() {
let list = ['Open a modal with component', 'Pass your data', 'Do something else', '...'];
this.bsModalRef = this.modalService.show(ModalContentComponent);
this.bsModalRef.content.title = 'Modal with component';
this.bsModalRef.content.list = list;
setTimeout(() => {
  list.push('PROFIT!!!');
}, 2000);
}
}

/* This is a component which we pass in modal*/

@Component({
 selector: 'modal-content',
 template: `
<div class="modal-header">
  <h4 class="modal-title pull-left">{{title}}</h4>
  <button type="button" class="close pull-right" aria-label="Close" (click)="bsModalRef.hide()">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<div class="modal-body">
  <ul *ngIf="list.length">
    <li *ngFor="let item of list">{{item}}</li>
  </ul>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-default" (click)="bsModalRef.hide()">Close</button>
</div>
 `
})
 export class ModalContentComponent {
  public title: string;
  public list: any[] = [];
  constructor(public bsModalRef: BsModalRef) {} // How do you get bsModalRef here

 }

使用

解决

import { BsModalRef } from 'ngx-bootstrap';

感谢 ngx-bootstap 社区 GitHub - Problem solution

这个问题是因为多重引用或循环引用。

您应该直接从 ngx-bootstrap 导入所有 ngx-bootstrap 组件和服务,而不是转到特定文件。

import { BsModalRef,ModalModule ,BsModalService } from 'ngx-bootstrap';

LIVE DEMO

通过导入解决了

import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';