首页 文章

Angular2 ng2-bs3-modal:每次模态关闭时如何执行函数?

提问于
浏览
0

我大部分都在工作,但是每次模态关闭时我都无法弄清楚如何执行函数 . 现在,如果你通过模态改变一些状态,关闭它,然后重新打开它,状态仍然会改变 . 但是,我希望每次关闭模态时都能调用"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( ) 函数?

谢谢!

3 回答

  • 1

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

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

    如果事件通过了一些事件args它应该是

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

    并且您的clear方法应该接收输入参数 .

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

    查看关于事件 Launcher 的本教程:https://toddmotto.com/component-events-event-emitter-output-angular-2

  • 0

    有正常的angular2 click事件来调用你的打字稿函数 (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();
        }
    }
    
  • 2

    除了Luis的回答之外,您还可以订阅组件中的事件 Launcher 并执行发射后面的一些操作,例如:

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

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

相关问题