【问题标题】:Angular2 ng2-bs3-modal: how to execute a function every time the modal closes?Angular2 ng2-bs3-modal:每次模态关闭时如何执行一个函数?
【发布时间】:2017-06-23 20:12:52
【问题描述】:

我正在使用 ng2-bs3-modal 库使用 Typescript 和 Angular 2 编写模式。它大部分都在工作,但我不知道如何让函数执行每次模态关闭。现在,如果您通过模态框更改某些状态,将其关闭,然后重新打开,则状态保持更改。但是,我希望能够在每次模态关闭时调用“clear()”函数(或执行其他一些行为)。

我在这里阅读了文档:https://github.com/dougludlow/ng2-bs3-modal,在我看来应该有一种方法可以在每次模态关闭时使用onClose EventEmitter 调用函数,但我可以'在任何地方都找不到如何做到这一点的示例。

这是我的代码的配对版本:

<modal #Modal>
<modal-header [show-close]="true">Header </modal-header>
<div class="modal-body">
    <form (ngSubmit)="onConfirm()">
        <label>NAME</label>
        <input type="text" [(ngModel)]="name"/>
    </form>
</div>

这是打字稿文件:

import { Component, Input, Output, EventEmitter, ViewChild } from "@angular/core"; 
import { MODAL_DIRECTIVES, ModalComponent } from "ng2-bs3-modal/ng2-bs3-modal"; 

@Component({ selector: "modal", templateUrl: "/modal.html", directives: [MODAL_DIRECTIVES] }) 

export class SaveSearchModalDirective { 

    @Output() Confirm = new EventEmitter<string>(); 
    @ViewChild("Modal") Modal: ModalComponent; 

    name: string; 
    constructor() { } 

    open() { 
        // do some things 
    } 

    clear() { 
        // do some things 
    } 

    onConfirm() { 
        // do more things 
        this.Confirm.emit(this.name); 
        this.close(); 
    } 
}

再次,我已经删除了所有细节,并且模态功能大部分都在工作。但是如何让我的clear( ) 函数在模式关闭时被调用每次

谢谢!

【问题讨论】:

  • 您是否测试过将函数绑定到模板中的发射器?

标签: angular modal-dialog


【解决方案1】:

可能您需要将html模板更改为:

<modal #Modal (onClose)="clear();">

如果事件通过了一些事件参数,它应该是

<modal #Modal (onClose)="clear($event);">

你的 clear 方法应该接收一个输入参数。

或许你也应该听听“onDismiss”事件...

查看有关事件发射器的教程: https://toddmotto.com/component-events-event-emitter-output-angular-2

【讨论】:

【解决方案2】:

有正常的 angular2 点击事件来调用你的打字稿函数 (click)="closeModal()"

<modal #myModal [keyboard]="false" [backdrop]="'static'">
        <modal-header>
           <button (click)="closeModal()"></button>
        </modal-header>
        <modal-body>
          //body
        </modal-body>
    </modal>

然后在你的组件中导入 ModalComponent

component.ts

    import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';

export class ModalExampleComponent {

    @ViewChild('myModal ')
    modal: ModalComponent;

    closeModal() {
       this.modal.close();
    }
}

【讨论】:

    【解决方案3】:

    除了Luis的回答,你还可以在你的组件中订阅事件发射器,并执行发射后面的一些动作,例如:

    @ViewChild('myModal ')
    modal: ModalComponent;
    
     ...
    ngOnInit() {
      ...
      this.modal.onClose.subscribe(_ => {
         // code to do something when the modal is closed
      }
      ...
    }
    

    您也可以以类似的方式使用 onOpen 和 onDismiss() EventEmitters。

    【讨论】:

      猜你喜欢
      • 2020-01-11
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      相关资源
      最近更新 更多