【问题标题】:Close ngx-modal opened from another component关闭从另一个组件打开的 ngx-modal
【发布时间】:2019-03-13 21:47:00
【问题描述】:

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

constructor(    
    private modalService: BsModalService
) {}

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

如何从 AboutComponent.ts 中关闭此模式,因为它没有对 bsModalRef 的引用?

关于组件.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>

关于组件.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() {
    ????????????
  }
}

【问题讨论】:

  • 查看 Event Emitter ,您可以轻松做到这一点。
  • @ThanveerShah 不,他不能,组件必须是父/子才能使用它们。至于 OP,使用你的模态服务来存储 ref,并将你的服务注入到 about 组件中。

标签: angular typescript


【解决方案1】:

理想的解决方案是:

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

constructor(public modalRef: BsModalRef) { }

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

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

【讨论】:

    【解决方案2】:

    创建一个服务来保留对您的模态(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();
     }
    }
    

    【讨论】:

      【解决方案3】:

      你可以这样试试:

      关于组件.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>
      

      【讨论】:

        猜你喜欢
        • 2011-01-12
        • 2018-06-12
        • 2020-11-29
        • 1970-01-01
        • 2013-10-31
        • 2018-11-08
        • 2021-03-23
        • 2021-12-19
        • 1970-01-01
        相关资源
        最近更新 更多