如何在Angular 2中使用代码打开模态?

时间:2016-02-15 02:56:58

标签: angular bootstrap-modal

通常我们会在data-target="#myModal"中使用<button>来打开模态。现在我需要使用代码来控制何时打开模态。

如果我使用[hidden]*ngIf来展示它,我需要删除class="modal fade",否则,模式永远不会显示。像这样:

<div [hidden]="hideModal" id="myModal">

但是,在这种情况下,删除class="modal fade"后,模式不会淡入并且背景中没有阴影。更糟糕的是,它将显示在屏幕底部而不是屏幕中心。

有没有办法保留class="modal fade"并使用代码打开它?

<button type="button" data-toggle="modal" data-target="#myModal">Open Modal</button>

<div id="myModal" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <p>Some text in the modal.</p>
      </div>
    </div>
  </div>
</div>

15 个答案:

答案 0 :(得分:36)

这是我发现的一种方式。您可以添加隐藏按钮:

<button id="openModalButton" [hidden]="true" data-toggle="modal" data-target="#myModal">Open Modal</button>

然后使用代码“点击”按钮打开模态:

document.getElementById("openModalButton").click();

这种方式可以保持模态的引导风格和动画中的淡入淡出。

答案 1 :(得分:20)

像往常一样在index.html中的脚本标记中包含jQuery。

在所有导入之后但在声明@Component之前,添加:

declare var $: any;

现在,您可以在Angular 2 TypeScript代码中随处使用jQuery:

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

参考:https://stackoverflow.com/a/38246116/2473022

答案 2 :(得分:10)

角度2或4 中实现此目的的简便方法(假设您使用 bootstrap 4

  

Component.html

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';
}

  

Component.ts

{{1}}

答案 3 :(得分:6)

这是我对modal bootstrap angular2组件的完整实现:​​

我假设您在 <script src="assets/js/jquery-2.1.1.js"></script> <script src="assets/js/bootstrap.min.js"></script> 标记底部的主index.html文件(包含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; } <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> 标记)中有:

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();
    }

}

modal.component.ts:

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

modal.html:

$.fn.gparent = function( recursion ){
   console.log( 'recursion: ' + recursion );
   if( recursion > 1 ) return $(this).parent().gparent( recursion - 1 );
   return $(this).parent();
};

客户端编辑器组件中的用法示例: 客户端 - 编辑component.ts:

<div id='grandparent'>
  <div id='parent'>
    <div id='child'>
      child
    </div>
  </div>
</div>

客户edit.html:

console.log( $('#child').gparent( 2 ) );

当然标题,showClose,mhead和mfoot是可选参数。

答案 4 :(得分:5)

我找到的最佳方式。将#lgModal或其他变量名称放在模态中。

在您看来:

<div bsModal #lgModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" (click)="lgModal.hide()" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title">Large modal</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
    </div>
  </div>
</div>

在您的组件中

import {Component, ViewChild, AfterViewInit} from '@angular/core';
import {CORE_DIRECTIVES} from '@angular/common';
// todo: change to ng2-bootstrap
import {MODAL_DIRECTIVES, BS_VIEW_PROVIDERS} from 'ng2-bootstrap/ng2-bootstrap';
import {ModalDirective} from 'ng2-bootstrap/ng2-bootstrap';


@Component({
  selector: 'modal-demo',
  directives: [MODAL_DIRECTIVES, CORE_DIRECTIVES],
  viewProviders:[BS_VIEW_PROVIDERS],
  templateUrl: '/app/components/modals/modalDemo.component.html'
})
export class ModalDemoComponent implements AfterViewInit{

  @ViewChild('childModal') public childModal: ModalDirective;
  @ViewChild('lgModal') public lgModal: ModalDirective;

  public showChildModal():void {
    this.childModal.show();
  }

  public hideChildModal():void {
    this.childModal.hide();
  }

  ngAfterViewInit() {
      this.lgModal.show();
  }

}

答案 5 :(得分:3)

我不认为将JQuery与angular和bootstrap一起使用不会有任何问题,因为添加bootstrap时会包含它。

  1. 在这样的进口之后立即添加美元


import {.......

declare var $: any;

@component.....
  1. modal应该具有这样的ID

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

  1. 然后有一个这样的方法

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

  1. 在单击按钮或您希望的任何位置调用该方法

答案 6 :(得分:2)

以下答案是针对最新的ng-bootstrap

安装

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

组件控制器

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);
  }

}

组件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>

答案 7 :(得分:1)

想想我找到了使用 ngx-bootstrap 执行此操作的正确方法。首先导入以下类:

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

在组件的类实现中添加一个@ViewCild属性,一个打开模态的函数,不要忘记将modalService设置为组件类构造函数中的私有属性:

@ViewChild('editSomething') editSomethingModal : TemplateRef<any>;
...

modalRef: BsModalRef;
openModal(template: TemplateRef<any>) {
  this.modalRef = this.modalService.show(template);
}
...
constructor(
private modalService: BsModalService) { }

&#39; editSomething&#39; @ViewChild声明的一部分是指组件模板文件及其模态模板实现( #editSomething ):

...
<ng-template #editSomething>
  <div class="modal-header">
  <h4 class="modal-title pull-left">Edit ...</h4>
  <button type="button" class="close pull-right" aria-label="Close" 
   (click)="modalRef.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)="modalRef.hide()"
        >Close</button>
  </div>
</ng-template>

最后调用方法在任何地方打开模态:

console.log(this.editSomethingModal);
this.openModal( this.editSomethingModal );
  

this.editSomethingModal   是一个 TemplateRef ,可以由ModalService显示。

瞧瞧!组件模板文件中定义的模态通过组件类实现中的调用显示。在我的例子中,我使用它来显示事件处理程序中的模态。

答案 8 :(得分:1)

我目前在Angular 8中使用Bootstrap 4.3,并希望以编程方式打开模式窗口(未如官方演示所示实际单击某些按钮)。

以下方法对我有用: 总体思路是创建与模式窗口关联的按钮。 首先确保单击此按钮后,它可以打开模态。 然后使用井号为该按钮标签提供一个ID,例如#hiddenBtn。 在组件ts文件中,import ViewChild from @angular/core并编写以下代码:

@ViewChild('hiddenBtn', {static: false}) myHiddenBtn;

此后,每当您想在组件ts代码中打开此模式窗口时,编写以下代码来模拟点击操作

this.myHiddenBtn.nativeElement.click();

答案 9 :(得分:0)

我过去常常没有大量编码的方式是... 我有隐藏按钮id="employeeRegistered"

在我的.ts文件import ElementRef from '@angular/core'

然后在我处理(click)方法的所有内容之后,执行以下操作:

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

然后模态按预期显示..

答案 10 :(得分:0)

对我来说,除了@ arjun-sk解决方案(link)之外,我还必须设置超时,因为我得到了error

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintBottom_toTopOf="@+id/button9"
        app:layout_constraintGuide_percent="0.5"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="0"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/button4"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintHorizontal_weight="2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button5"
        app:layout_constraintVertical_bias="1.0" />

    <Button
        android:id="@+id/button3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="="
        app:layout_constraintBottom_toBottomOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintStart_toEndOf="@+id/button4"
        app:layout_constraintTop_toTopOf="@+id/button" />

    <Button
        android:id="@+id/button4"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="."
        app:layout_constraintBottom_toBottomOf="@+id/button"
        app:layout_constraintEnd_toStartOf="@+id/button3"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toTopOf="@+id/button" />

    <Button
        android:id="@+id/button5"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="1"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toStartOf="@+id/button6"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button17" />

    <Button
        android:id="@+id/button6"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="2"
        app:layout_constraintBottom_toBottomOf="@+id/button5"
        app:layout_constraintEnd_toStartOf="@+id/button7"
        app:layout_constraintStart_toEndOf="@+id/button5"
        app:layout_constraintTop_toTopOf="@+id/button5" />

    <Button
        android:id="@+id/button7"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="3"
        app:layout_constraintBottom_toBottomOf="@+id/button5"
        app:layout_constraintEnd_toStartOf="@+id/button8"
        app:layout_constraintStart_toEndOf="@+id/button6"
        app:layout_constraintTop_toTopOf="@+id/button5" />

    <Button
        android:id="@+id/button8"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="+"
        app:layout_constraintBottom_toBottomOf="@+id/button5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/button7"
        app:layout_constraintTop_toTopOf="@+id/button5" />

    <Button
        android:id="@+id/button9"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="AC"
        app:layout_constraintBottom_toTopOf="@+id/button21"
        app:layout_constraintEnd_toStartOf="@+id/button10"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline" />

    <Button
        android:id="@+id/button10"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="+/-"
        app:layout_constraintBottom_toBottomOf="@+id/button9"
        app:layout_constraintEnd_toStartOf="@+id/button11"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toEndOf="@+id/button9"
        app:layout_constraintTop_toTopOf="@+id/guideline" />

    <Button
        android:id="@+id/button11"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="%"
        app:layout_constraintBottom_toBottomOf="@+id/button9"
        app:layout_constraintEnd_toStartOf="@+id/button12"
        app:layout_constraintStart_toEndOf="@+id/button10"
        app:layout_constraintTop_toTopOf="@+id/guideline" />

    <Button
        android:id="@+id/button12"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="+"
        app:layout_constraintBottom_toBottomOf="@+id/button9"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/button11"
        app:layout_constraintTop_toTopOf="@+id/guideline" />


    <Button
        android:id="@+id/button17"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="4dp"
        android:text="4"
        app:layout_constraintBottom_toTopOf="@+id/button5"
        app:layout_constraintEnd_toStartOf="@+id/button18"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button21" />

    <Button
        android:id="@+id/button18"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="5"
        app:layout_constraintBottom_toBottomOf="@+id/button17"
        app:layout_constraintEnd_toStartOf="@+id/button19"
        app:layout_constraintStart_toEndOf="@+id/button17"
        app:layout_constraintTop_toTopOf="@+id/button17" />

    <Button
        android:id="@+id/button19"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="6"
        app:layout_constraintBottom_toBottomOf="@+id/button17"
        app:layout_constraintEnd_toStartOf="@+id/button20"
        app:layout_constraintStart_toEndOf="@+id/button18"
        app:layout_constraintTop_toTopOf="@+id/button17" />

    <Button
        android:id="@+id/button20"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="-"
        app:layout_constraintBottom_toBottomOf="@+id/button17"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/button19"
        app:layout_constraintTop_toTopOf="@+id/button17" />

    <Button
        android:id="@+id/button21"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="7"
        app:layout_constraintBottom_toTopOf="@+id/button17"
        app:layout_constraintEnd_toStartOf="@+id/button22"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button9" />

    <Button
        android:id="@+id/button22"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="8"
        app:layout_constraintBottom_toBottomOf="@+id/button21"
        app:layout_constraintEnd_toStartOf="@+id/button23"
        app:layout_constraintStart_toEndOf="@+id/button21"
        app:layout_constraintTop_toTopOf="@+id/button21" />

    <Button
        android:id="@+id/button23"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="9"
        app:layout_constraintBottom_toBottomOf="@+id/button21"
        app:layout_constraintEnd_toStartOf="@+id/button24"
        app:layout_constraintStart_toEndOf="@+id/button22"
        app:layout_constraintTop_toTopOf="@+id/button21" />

    <Button
        android:id="@+id/button24"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="x"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/button21"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/button23"
        app:layout_constraintTop_toTopOf="@+id/button21" />

</android.support.constraint.ConstraintLayout>

答案 11 :(得分:0)

我正在使用变量来控制显示和隐藏,并依靠按钮来打开模态

ts代码:

showModel(){
  this.showModal = true;
}

html:

<button type="button" data-toggle="modal" data-target="#myModal" (click)="showModel()>Open Modal</button>

<div *ngIf="showModal" >
  <div id="myModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <p>Some text in the modal.</p>
            </div>
        </div>
    </div>
</div>

答案 12 :(得分:0)

我们可以使用jquery打开引导程序模式。

ngAfterViewInit() { 
      $('#scanModal').modal('show'); 
}

答案 13 :(得分:0)

@ ng-bootstrap / ng-bootstrap npm我在项目引导程序中使用的是它,用于材料,我们使用了对话框

HTML代码

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

模式模板

<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文件

import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';

constructor(
    private modalService: NgbModal
  ) { }

  openModal(modalContent){
     this.modalService.open(modalContent, { centered: true});
   }

答案 14 :(得分:0)

简单地说, Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/winrm/__init__.py", line 52, in run_ps rs = self.run_cmd('powershell -encodedcommand {0}'.format(encoded_ps)) File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/winrm/__init__.py", line 39, in run_cmd shell_id = self.protocol.open_shell() File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/winrm/protocol.py", line 166, in open_shell res = self.send_message(xmltodict.unparse(req)) File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/winrm/protocol.py", line 243, in send_message resp = self.transport.send_message(message) File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/winrm/transport.py", line 323, in send_message response = self._send_message_request(prepared_request, message) File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/winrm/transport.py", line 333, in _send_message_request raise InvalidCredentialsError("the specified credentials were rejected by the server") winrm.exceptions.InvalidCredentialsError: the specified credentials were rejected by the server 尝试将打字版本与您的引导程序版本相匹配。例如。你有 Bootstrap 4.3.1 然后 npm install --save @types/bootstrap