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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用代码在Angular 2中打开模态?相关的知识,希望对你有一定的参考价值。

通常我们在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>
答案

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

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

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

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

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

另一答案

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

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>

另一答案

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

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

declare var $: any;

现在,您可以在Angular 2 TypeScript代码中的任何位置自由使用jQuery:

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

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

另一答案

在角度2或4中实现此目的的简单方法(假设您使用的是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>
另一答案

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

我假设你在<html>标签底部的主index.html文件(使用<body><body>标签)中有:

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

客户端编辑器组件中的用法示例: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();
    


客户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和mfoot ar可选参数。

另一答案

我找到的最佳方式。将#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();
  

以上是关于如何使用代码在Angular 2中打开模态?的主要内容,如果未能解决你的问题,请参考以下文章

如何从 ag-grid 单元格中打开模态对话框单击 Angular 6

如何使用 @angular/cdk 使 NgbModal 可拖动

每次打开时如何使 div 模态滚动到顶部?

如何在模态窗口 [ANGULAR 5] 内创建路由?

使用 Angular 调用 href 打开模态

如何在打字稿中使用 angular-ui-bootstrap(模态)?