关闭从另一个组件打开的ngx-modal

时间:2019-03-13 11:09:26

标签: angular typescript

我有一个使用以下代码在单击按钮时显示模式的组件:

constructor(    
    private modalService: BsModalService
) {}

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

由于没有引用bsModalRef,因此如何从AboutComponent.ts中关闭此模式?

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() {
    ????????????
  }
}

3 个答案:

答案 0 :(得分:0)

创建一个保留对模态(bsModalRef)的引用的服务,并将其注入到两个组件中。像这样的东西。

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

答案 1 :(得分:0)

嘿,您可以这样尝试:

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>

答案 2 :(得分:0)

理想的解决方案是:

在AboutComponent.ts中,我们必须注入BsModalRef而不是BsModalService:

constructor(public modalRef: BsModalRef) { }

这样做,只需在模板中更改click事件:

<button type="button" class="btn btn-default" (click)="modalRef.hide()">Fechar</button>