触发NgbModal没有按钮但通过函数调用

时间:2018-01-04 16:13:36

标签: angular typescript ng-bootstrap

Angular Bootstrap's Modals中的所有示例都有一个外部按钮来触发模态本身。

在我的情况下,我使用的是一个函数nodeClicked(event, node)的图。

在函数中,我检查用户是否在点击节点时按下 CTRL 按钮。如果没有,我需要触发一个Modal,说明没有点击该按钮。

component.html

<ng-template #content let-c="close" let-d="dismiss">
    <div class="modal-header">
        <h4 class="modal-title">Warning</h4>
        <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <div class="modal-body">
        <p>NO <kbd>CTRL</kbd> Button Pressed.</p>
        <p>If previous Selection were selected using Multiselect Feature, they will be deleted.</p>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-outline-dark" (click)="c('Close click')">Close</button>
    </div>
</ng-template>

nodeClicked()函数中:

component.ts

constructor (modal: NgbModal) {}
....
nodeClicked(ev, node) {

if (ev.control) {
  //perform necessary stuff
}
else {
  this.modal.open() // here according to API I need to pass content.
  // but I already have mentioned that in `modal-body`
}

}

如何在content方法调用中实际传递this.model.open()字符串的情况下触发我的模态?

1 个答案:

答案 0 :(得分:4)

您可以在组件代码中使用@ViewChild("content")获取模态模板的引用,并将其传递给NgbModal.open。例如,this plunker会在5秒后自动显示模态。

import { Component, ViewChild, TemplateRef } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

export class MyComponent {

  @ViewChild("content") modalContent: TemplateRef<any>;

  constructor(private modal: NgbModal) {
  }

  nodeClicked(ev, node) {
    if (ev.control) {
      //perform necessary stuff
    }
    else {
      this.modal.open(this.modalContent).result.then((result) => {
        ...
      });
    }
  }
}