【问题标题】:How to close the existing ngx-modal when new modal open up from same component in Angular 8从Angular 8中的同一组件打开新模式时如何关闭现有的ngx-modal
【发布时间】:2021-03-27 09:54:53
【问题描述】:

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

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

下面是我的堆栈闪电战。

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

【问题讨论】:

    标签: angular typescript ngx-bootstrap ngx-modal


    【解决方案1】:

    我会使用一种模式...

    这里是策略

    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, config, 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

    【讨论】:

    • 但是在 app.component 中保持订阅状态是一种好习惯吗?
    • 只要您确保退订,我相信没问题。另一种选择是简单地将模态移动到它自己的组件。这样你就不用担心在 app.component 中订阅了
    • 酷。您是否可以提供模态的示例作为自己的组件...?提前致谢
    • 看到这个分叉stackblitz.com/edit/…
    • 谢谢..只是一个建议..你知道任何支持这个功能的图书馆,比如Angular 8中的材料stackoverflow.com/questions/66802189/…
    猜你喜欢
    • 1970-01-01
    • 2019-05-06
    • 2021-03-23
    • 1970-01-01
    • 2020-09-03
    • 2021-01-31
    • 1970-01-01
    • 2019-09-30
    • 2020-11-29
    相关资源
    最近更新 更多