trigger NgbModal without a button but via function call

青春壹個敷衍的年華 提交于 2019-12-08 03:33:01

问题


All the examples in Angular Bootstrap's Modals have an external button to trigger the modal itself.

In my case I am using a Diagram, which has a function nodeClicked(event, node).

In the function I check whether the user has pressed the CTRL button whilst clicking the node. If not, I need to trigger a Modal stating that the button is not clicked.

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>

within the nodeClicked() function:

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`
}

}

How Can i Trigger my Modal without actually passing the content string in the this.model.open() method call?


回答1:


You can get a reference to the modal template with @ViewChild("content") in the component code, and pass it to NgbModal.open. As an example, this plunker displays the modal automatically after 5 seconds.

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) => {
        ...
      });
    }
  }
}


来源:https://stackoverflow.com/questions/48099246/trigger-ngbmodal-without-a-button-but-via-function-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!