ngx-bootstrap How to open a modal from another component?

一世执手 提交于 2019-12-01 17:09:47

If you're trying to open a Modal Component from another Component, then this is the right way to do it with ngx-bootstrap:

import { Component } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';

/* This is the Component from which we open the Modal Component */
@Component({
  selector: 'my-component',
  templateUrl: './service-component.html'
})
export class MyComponent {
  bsModalRef: BsModalRef;
  constructor(private modalService: BsModalService) {}

  public openModalWithComponent() {
    /* this is how we open a Modal Component from another component */
    this.bsModalRef = this.modalService.show(ModalContentComponent);
  }
}

/* This is the Modal Component */
@Component({
  selector: 'child-modal',
  template: `
    <div class="modal-header">
      <h4 class="modal-title pull-left">Title</h4>
      <button type="button" class="close pull-right" aria-label="Close" (click)="bsModalRef.hide()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      ...
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" (click)="bsModalRef.hide()">Close</button>
    </div>
  `
})
export class ChildModalComponent {
  constructor(public bsModalRef: BsModalRef) {}
}

template of the Component which is calling the Modal:

<button type="button" class="btn btn-primary" (click)="openModalWithComponent()">Create modal with component</button>

So you should NOT include the Modal Component in the template like this:

 <child-modal #childModal ></child-modal>

Official doc:

https://valor-software.com/ngx-bootstrap/#/modals#service-component

If you use same component then, 

HTML #
    <button (click)="openModalWithComponent()">open</button>

    // for display purpose
    <ng-template #template>
      <div class="modal-body">
      </div>
    </ng-template>

COMPONENT #
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
import { BsModalService } from 'ngx-bootstrap/modal';
import { ViewChild, ElementRef } from '@angular/core';

      bsModalRef: BsModalRef;
constructor(private modalService: BsModalService) {}
      @ViewChild('template') elementView: ElementRef;
    openModalWithComponent() {    
        this.bsModalRef = this.modalService.show(this.elementView);
        // this.bsModalRef.content.closeBtnName = 'Close';
        // (click)="bsModalRef.hide()"

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