微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当从 Angular 8 中的同一组件打开新模态时如何关闭现有的 ngx-modal

如何解决当从 Angular 8 中的同一组件打开新模态时如何关闭现有的 ngx-modal

我正在尝试制作一个可以从同一个模态本身调用的可重用模态组件。

如何配置组件和模态,以便在可重用组件打开时,旧实例将直接关闭

下面是我的stackblitz。

https://stackblitz.com/edit/angular-nested-component-modal-ngx-bootstrap-n

解决方法

我会使用一种模态...

这是策略

  1. 在应用组件上有模态
  2. 创建一个服务,当用户想要打开一个新的模式时进行通信
  3. 从每个组件按钮调用服务

让我们从定义我们的服务开始

my.service.ts

import { Injectable } from "@angular/core";
import { BehaviorSubject,Subject } from "rxjs";

interface IModalParams {
  component: any;
  config?: any;
  title?: any;
}
@Injectable()
export class MyService {
  modalOpen$ = new BehaviorSubject(false);
  component;
  config;
  title;
  show({ component,config,title }: IModalParams) {
    this.component = component;
    this.config = config;
    this.title = title;
    this.modalOpen$.next(true);
  }
}

所以我们定义了一个 show 方法来设置一些变量(componentconfigurationtitle

我们还定义了一个主题 modalOpen$。现在,当用户打开一个新的模态时,任何订阅它的属性都会被通知

app.component.ts

  ngOnInit() {
    this.myService.modalOpen$.pipe(
      tap(() => this.modalRef?.hide()),filter(isOpen => isOpen)
    ).subscribe({
      next: () => {
        const {component,title} = this.myService
          this.modalRef = this.modalService.show(component,config);
          if(title) {
            this.modalRef.content.title = title; 
          }
      }
    })
  }

这里我们订阅 modalOpen$ 并打开或关闭提供的组件

any-other.component.ts

 this.myService.show({
     component: ModalContentComponent,config: {
      ignoreBackdropClick: false
    },title: "Modal with component"
   })
  }

在其他组件中,我们现在可以使用上面指定的 show 方法

See Demo Here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。