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

Abhijit Muke picture Abhijit Muke · Aug 3, 2017 · Viewed 10k times · Source

I'm quite new to Angular 4.I have been working on Angular 1.5.x and now converting same application in Angular 4 with ngUpgrade hybrid approach. I'm using ngx-bootstrap modal component in my hybrid application in order to replace existing modal service.

I found some problem in following guide ngx-bootstrap-modal with service.

Having problem with this statement If you passed a component to .show() you can get access to opened modal by injecting BsModalRef

I'm copying same example here,

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

I try running this example, but I never get bsModalRef in opened modal.

I also try passing bsModalRef through content, but it work with one modal and failed to work with nested modal.

Is there any other way to pass bsModalRef in ModalContentComponent ?

Find complete example here,

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

 }

Answer

Aravind picture Aravind · Aug 5, 2017

This issue is because of multiple references or circular references.

You should import all the ngx-bootstrap components, services directly from the ngx-bootstrap instead of going to the specific file.

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

LIVE DEMO