0

I have a component that shows up a modal when click a button, using this code:

constructor(    
    private modalService: BsModalService
) {}

showModal() {
    this.bsModalRef = this.modalService.show(AboutComponent);
}

How to close this modal from the AboutComponent.ts since it does not have a reference to bsModalRef?

AboutComponent.html:

<div class="modal-header">
  <h4 class="modal-title pull-left">teste</h4>
  <button type="button" class="close pull-right" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<div class="modal-body">
  <h1>teste</h1>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-default" (click)="closeModal()">Fechar</button>
</div>

AboutComponent.ts

import { Component, OnInit } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap';

@Component({
  selector: 'app-about',
  templateUrl: './about.component.html',
  styleUrls: ['./about.component.scss']
})
export class AboutComponent implements OnInit {

  constructor(private modalService: BsModalService) { }

  ngOnInit() {

  }

  closeModal() {
    ????????????
  }
}
Beetlejuice
  • 4,292
  • 10
  • 58
  • 84
  • Check out Event Emitter , You can easily do it with that. – Thanveer Shah Mar 13 '19 at 11:17
  • @ThanveerShah no he cannot, components have to be parent/child to use them. As for the OP, use your modal service to store the ref, and inject your service into the about component. –  Mar 13 '19 at 11:25

3 Answers3

2

The ideal solution is:

At the AboutComponent.ts we have to inject BsModalRef instead of BsModalService:

constructor(public modalRef: BsModalRef) { }

Doing so, in the template just change the click event:

<button type="button" class="btn btn-default" (click)="modalRef.hide()">Fechar</button>
Beetlejuice
  • 4,292
  • 10
  • 58
  • 84
0

Create a service that keeps a reference to your modal (bsModalRef), and inject it into both of you components. Something like this.

@Injectable({
providedIn: 'root'
})
export class RemoteModalControlSerice{
 myModalRef:any;
 setModalRef(modalRef:any){
  this.myModalRef = modalRef;
 }
 closeModal(){
  if(!this.myModalRef){
  // throw some exception
  }
  this.myModalRef.close();
 }
}
Bogdan B
  • 846
  • 9
  • 23
0

Hey you can try like this:

AboutComponent.html:

<div class="modal-header">
  <h4 class="modal-title pull-left">teste</h4>
  <button type="button" class="close pull-right" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<div class="modal-body">
  <h1>teste</h1>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-default" 
    (click)="modal.dismiss('Cross click')">Fechar</button>
</div>
Yash Rami
  • 2,276
  • 1
  • 10
  • 16