【问题标题】:(ngx-bootstrap) Close a modal that has been created with a component programmatically(ngx-bootstrap)以编程方式关闭已使用组件创建的模式
【发布时间】:2018-05-25 22:01:31
【问题描述】:

我有一个使用 ngx-bootstrap 的 Angular 5 应用程序。 我使用Modal Component 创建了两个模态。我需要在一段时间后关闭第一个模态,然后打开第二个模态。

我在打开第二个模式之前尝试了这两种方法,但是...

  • ...当我在显示模态的组件中使用this.modalService.hide(0) 时,没有任何反应
  • ...当我在显示模态的组件中使用this.modalService.hide(1) 时,第二个模态会立即打开和关闭

this.modalReference.hide() 也没有这样做。

任何建议都非常感谢!

【问题讨论】:

    标签: angular ngx-bootstrap ngx-bootstrap-modal


    【解决方案1】:

    我设法让您的场景与以下实现一起工作

    在 app.component.html 中

    <div bsModal #modalone="bs-modal" class="modal fade" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Modal ONe</h4>
                </div>
                <div class="modal-body">
                    <button (click)="toggle()">Toggle</button>
                </div>
            </div>
        </div>
    </div>
    
    <div bsModal #modaltwo="bs-modal" class="modal fade" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Modal Two</h4>
                </div>
                <div class="modal-body">
                    <button (click)="toggle()">Toggle</button>
                </div>
            </div>
        </div>
    </div>
    

    在上述模态部分中,请注意两件重要的事情; 1) 每个模态部分都通过bsModal 引用模态指令 2) 使用#...引用元素节点...此外,引用必须具有不同的名称...在此示例中,我选择了使用#modalone#modaltwo。这里的每个引用都传递了一个 ModalDirective 的实例。

    在 app.component.ts 中,使用 @ViewChild() 装饰器和上面使用的引用名称获取模态元素的引用。 (在这里查看完整文档https://angular.io/api/core/ViewChild

     @ViewChild('modalone') public modalone: ModalDirective;
     @ViewChild('modaltwo') public modaltwo: ModalDirective;
    
     // Required to toggle
     one: boolean = true;
    

    在您的ngAfterViewInit() 生命周期挂钩中,使用show() 函数切换第一个模式。初始 show() 调用在 AfterViewInit 生命周期挂钩中执行,以便获得元素的节点。这将启用第一个模式。

    ngAfterViewInit(): void {
        this.modalone.show();
    }
    

    添加一个简单的切换功能(在上面的模态html中引用)以在两个模态之间切换。

    toggle() {
        if (this.one) {
            this.modalone.hide();
            this.modaltwo.show();
        } else {
            this.modalone.show();
            this.modaltwo.hide();
        }
    
        this.one = !this.one;
    }
    

    这应该演示您需要的两个模态之间的切换...这是一个工作 plunker https://plnkr.co/edit/F5oWAI?p=preview

    【讨论】:

    • 谢谢!这对我的特定问题不起作用,因为 ModalComponent 不使用 ModalDirective 但答案非常好。对于任何想知道我的解决方案是什么的人:我必须使用 setTimeout,因为 ModalService.show 和 ModalService 的 onShown 事件在显示模式之前返回。
    猜你喜欢
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 2011-04-14
    • 1970-01-01
    相关资源
    最近更新 更多