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

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

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

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

    Include jQuery as usual inside script tags in index.html.

    After all the imports but before declaring @Component, add:

    declare var $: any;
    

    Now you are free to use jQuery anywhere in your Angular 2 TypeScript code:

    $("#myModal").modal('show');
    

    Reference: https://stackoverflow.com/a/38246116/2473022

    0 讨论(0)
  • 2020-12-05 04:57

    Here is my full implementation of modal bootstrap angular2 component:

    I assume that in your main index.html file (with <html> and <body> tags) at the bottom of <body> tag you have:

      <script src="assets/js/jquery-2.1.1.js"></script>
      <script src="assets/js/bootstrap.min.js"></script>
    

    modal.component.ts:

    import { Component, Input, Output, ElementRef, EventEmitter, AfterViewInit } from '@angular/core';
    
    declare var $: any;// this is very importnant (to work this line: this.modalEl.modal('show')) - don't do this (becouse this owerride jQuery which was changed by bootstrap, included in main html-body template): let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');
    
    @Component({
      selector: 'modal',
      templateUrl: './modal.html',
    })
    export class Modal implements AfterViewInit {
    
        @Input() title:string;
        @Input() showClose:boolean = true;
        @Output() onClose: EventEmitter<any> = new EventEmitter();
    
        modalEl = null;
        id: string = uniqueId('modal_');
    
        constructor(private _rootNode: ElementRef) {}
    
        open() {
            this.modalEl.modal('show');
        }
    
        close() {
            this.modalEl.modal('hide');
        }
    
        closeInternal() { // close modal when click on times button in up-right corner
            this.onClose.next(null); // emit event
            this.close();
        }
    
        ngAfterViewInit() {
            this.modalEl = $(this._rootNode.nativeElement).find('div.modal');
        }
    
        has(selector) {
            return $(this._rootNode.nativeElement).find(selector).length;
        }
    }
    
    let modal_id: number = 0;
    export function uniqueId(prefix: string): string {
        return prefix + ++modal_id;
    }
    

    modal.html:

    <div class="modal inmodal fade" id="{{modal_id}}" tabindex="-1" role="dialog"  aria-hidden="true" #thisModal>
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header" [ngClass]="{'hide': !(has('mhead') || title) }">
                    <button *ngIf="showClose" type="button" class="close" (click)="closeInternal()"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <ng-content select="mhead"></ng-content>
                    <h4 *ngIf='title' class="modal-title">{{ title }}</h4>
                </div>
                <div class="modal-body">
                    <ng-content></ng-content>
                </div>
    
                <div class="modal-footer" [ngClass]="{'hide': !has('mfoot') }" >
                    <ng-content select="mfoot"></ng-content>
                </div>
            </div>
        </div>
    </div>
    

    And example of usage in client Editor component: client-edit-component.ts:

    import { Component } from '@angular/core';
    import { ClientService } from './client.service';
    import { Modal } from '../common';
    
    @Component({
      selector: 'client-edit',
      directives: [ Modal ],
      templateUrl: './client-edit.html',
      providers: [ ClientService ]
    })
    export class ClientEdit {
    
        _modal = null;
    
        constructor(private _ClientService: ClientService) {}
    
        bindModal(modal) {this._modal=modal;}
    
        open(client) {
            this._modal.open();
            console.log({client});
        }
    
        close() {
            this._modal.close();
        }
    
    }
    

    client-edit.html:

    <modal [title]='"Some standard title"' [showClose]='true' (onClose)="close()" #editModal>{{ bindModal(editModal) }}
        <mhead>Som non-standart title</mhead>
        Some contents
        <mfoot><button calss='btn' (click)="close()">Close</button></mfoot>
    </modal>
    

    Ofcourse title, showClose, mhead and mfoot ar optional parameters.

    0 讨论(0)
  • 2020-12-05 04:57

    For me I had to settimeout in addition to @arjun-sk solution's (link), as I was getting the error

    setTimeout(() => {
          this.modalService.open(this.loginModal, { centered: true })
        }, 100); 
    
    0 讨论(0)
  • 2020-12-05 04:58

    I do not feel there is anything wrong with using JQuery with angular and bootstrap, since it is included when adding bootstrap.

    1. Add the $ right after the imports like this


    import {.......
    
    declare var $: any;
    
    @component.....
    
    1. modal should have an id like this

    <div id="errorModal" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" ..............

    1. then have a method like this

    showErrorModal() { $("#errorModal").modal('show'); }

    1. call the method on a button click or anywhere you wish
    0 讨论(0)
  • 2020-12-05 04:58

    @ng-bootstrap/ng-bootstrap npm I m using for this as in the project bootstrap is used, for material, we used dialog

    HTML Code

      <span (click)="openModal(modalRef)" class="form-control input-underline pl-3 ">Open Abc Modal
     </span>
    

    Modal template

    <ng-template class="custom-modal"  #modalRef let-c="close" let-d="dismiss">
       <div class="modal-header custom-modal-head"><h4 class="modal-title">List of Countries</h4>
         <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
             <img src="assets/actor/images/close.png" alt="">
          </button>
      </div>
      <div class="modal-body country-select">
           <div class="serch-field">
               <div class="row">
                   <div class="col-md-12">
                     <input type="text"  class="form-control input-underline pl-3" placeholder="Search Country"
                        [(ngModel)]="countryWorkQuery" [ngModelOptions]="{standalone: true}">
                     <ul *ngIf="countries" class="ng-star-inserted">
                       <li (click)="setSelectedCountry(cntry, 'work');d('Cross click');" class="cursor-pointer"
                       *ngFor="let cntry of countries | filterNames:countryWorkQuery ">{{cntry.name}}</li>
                     </ul>
                     <span *ngIf="!modalSpinner && (!countries || countries.length<=0)">No country found</span>
                     <span *ngIf="modalSpinner" class="loader">
                         <img src="assets/images/loader.gif" alt="loader">
                     </span>
                   </div>
                 </div>
           </div>
     </div>
    </ng-template>
    

    Ts File

    import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';
    
    constructor(
        private modalService: NgbModal
      ) { }
    
      openModal(modalContent){
         this.modalService.open(modalContent, { centered: true});
       }
    
    0 讨论(0)
  • 2020-12-05 05:03

    The below answer is in reference to the latest ng-bootstrap

    Install

    npm install --save @ng-bootstrap/ng-bootstrap
    

    app.module.ts

    import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
    
    @NgModule({
      declarations: [
        ...
      ],
      imports: [
        ...
    
        NgbModule
    
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    Component Controller

    import { TemplateRef, ViewChild } from '@angular/core';
    import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
    
    @Component({
      selector: 'app-app-registration',
      templateUrl: './app-registration.component.html',
      styleUrls: ['./app-registration.component.css']
    })
    
    export class AppRegistrationComponent implements OnInit {
    
      @ViewChild('editModal') editModal : TemplateRef<any>; // Note: TemplateRef
    
      constructor(private modalService: NgbModal) { }
    
      openModal(){
        this.modalService.open(this.editModal);
      }
    
    }
    

    Component HTML

    <ng-template #editModal let-modal>
    
    <div class="modal-header">
      <h4 class="modal-title" id="modal-basic-title">Edit Form</h4>
      <button type="button" class="close" aria-label="Close" (click)="modal.dismiss()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    
    <div class="modal-body">
      
      <form>
        <div class="form-group">
          <label for="dateOfBirth">Date of birth</label>
          <div class="input-group">
            <input id="dateOfBirth" class="form-control" placeholder="yyyy-mm-dd" name="dp" ngbDatepicker #dp="ngbDatepicker">
            <div class="input-group-append">
              <button class="btn btn-outline-secondary calendar" (click)="dp.toggle()" type="button"></button>
            </div>
          </div>
        </div>
      </form>
    
    </div>
    
    <div class="modal-footer">
      <button type="button" class="btn btn-outline-dark" (click)="modal.close()">Save</button>
    </div>
    
    </ng-template>
    
    0 讨论(0)
提交回复
热议问题