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

标签 angular typescript ngx-bootstrap ngx-modal

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

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

下面是我的 stackblitz。

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

最佳答案

我会使用一个模式...

这是策略

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

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

我的服务.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$。现在,当用户打开新模式时,任何订阅此属性的属性都会收到通知

应用程序组件.ts

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

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

任何其他.component.ts

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

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

See Demo Here

关于angular - 当从 Angular 8 中的同一组件打开新模态时如何关闭现有的 ngx-modal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66786004/

相关文章:

javascript - 在 Angular2 应用程序中使用字符串插值从数组中提取值

Angular 路由 canActivate AuthGuard 传输查询参数

typescript - 阿多尼斯 5 "make:migration command not found"有什么想法吗?

angular - 在 ngx-bootstrap 模式中将参数发送到 onHide 事件

javascript - Angular2 - 在用户更改后重置选择的值

angular - 如何修复 "Module build failed (from ./node_modules/postcss-loader/src/index.js)"

typescript - 在 Visual Studio 2015 中从 *.ts 生成 *.js

typescript - 有什么方法可以在 tsconfig 中设置严格模式下使用 Loopback 4?

angular - 在 Angular 4 中生产构建后日期选择器样式不起作用

angular - Ng2 Bootstrap 的日期选择器在无法读取 getFullYear() 时不断抛出错误