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

时间:2017-08-03 04:56:37

标签: angularjs angular ng2-bootstrap modalpopup ngx-bootstrap

我是Angular 4的新手。我一直致力于Angular 1.5.x,现在使用ngUpgrade混合方法在Angular 4中转换相同的应用程序。 我在混合应用程序中使用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,但它可以使用一个模态,但无法使用嵌套模态。

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

在此处查找完整示例,

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

 }

3 个答案:

答案 0 :(得分:1)

此问题是由于多个引用或循环引用。

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

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

<强> LIVE DEMO

答案 1 :(得分:0)

使用

解决
  

从'ngx-bootstrap'导入{BsModalRef};

感谢GitHub上的// v--- use the Kotlin function type here fun <T, R> Flowable<T>.then(mapper: (T) -> Publisher<R>): Flowable<R> { return flatMap(mapper) } 社区 - Problem solution

答案 2 :(得分:0)

通过导入解决了

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