How to use code to open a modal in Angular 2?

前端 未结 14 2972
天涯浪人
天涯浪人 2020-12-05 04:34

Usually we use data-target=\"#myModal\" in the

相关标签:
14条回答
  • 2020-12-05 05:03

    The Way i used to do it without lots of coding is.. I have the hidden button with the id="employeeRegistered"

    On my .ts file I import ElementRef from '@angular/core'

    Then after I process everything on my (click) method do as follow:

    this.el.nativeElement.querySelector('#employeeRegistered').click();

    then the modal displays as expected..

    0 讨论(0)
  • 2020-12-05 05:10

    Easy way to achieve this in angular 2 or 4 (Assuming that you are using bootstrap 4)

    Component.html

    <button type="button" (click)="openModel()">Open Modal</button>
    
    <div #myModel class="modal fade">
      <div class="modal-dialog">
        <div class="modal-content">
         <div class="modal-header">
            <h5 class="modal-title ">Title</h5>
            <button type="button" class="close" (click)="closeModel()">
                <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <p>Some text in the modal.</p>
          </div>
        </div>
      </div>
    </div>

    Component.ts

    import {Component, OnInit, ViewChild} from '@angular/core';
    
    @ViewChild('myModal') myModal;
    
    openModel() {
      this.myModal.nativeElement.className = 'modal fade show';
    }
    closeModel() {
       this.myModal.nativeElement.className = 'modal hide';
    }
    
    0 讨论(0)
提交回复
热议问题