如何关闭一个Angular Bootstrap 模态框

15
我正在使用Angular 4、Firebase和Angular Bootstrap开发。我打开了一个模态框,其中包含一个用户表单,并且想要在用户使用其中一种方法登录(谷歌认证、Facebook认证或电子邮件和密码认证)后立即关闭模态框。但我无法找到必要的方式来在需要时关闭模态框。
谷歌认证
    export class NavComponent implements OnInit {

          @ViewChild('close') public modal: ElementRef;
    
          constructor() {}
    
    
          public openModal(content) {
            this.modalService.open(content).result.then((result) => {
              this.closeResult = `Closed with: ${result}`;
            }, (reason) => {
              this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
            });
          }    
          private getDismissReason(reason: any): string {
            if (reason === ModalDismissReasons.ESC) {
              return 'by pressing ESC';
            } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
              return 'by clicking on a backdrop';
            } else {
              return `with: ${reason}`;
            }
          }
         public googleLogin(content): void {
           this.auth.googleAuth().then((res: any) => {
              // close the modal in this moment.
              this.modal.nativeElement.click();
              const user = res.user;
              this.router.navigate(['/gallery']);
            });
         }}

弹出窗口HTML

<ng-template #login let-c="close" let-d="dismiss" class="modal-dialog">
  <button #close type="button" class="close" aria-label="Close" (click)="d('Cross click')">
    <span aria-hidden="true">&times;</span>
  </button>
  <div class="modal-body">
    <ngb-tabset>
      <ngb-tab title="Couple">
        <ng-template ngbTabContent>
          <div class="modal-header">
            <h4 class="modal-title">Couple</h4>
          </div>
          <form [formGroup]="loginForm" (ngSubmit)="userlogin(user)" novalidate>
            <div id="couple_login_form" class="login-form">
              <div class="login-field" [ngClass]="{'pattern' : loginForm.controls.email.invalid && loginForm.controls.email.dirty, 'error' : loginForm.controls.email.pristine && loginForm.controls.email.touched, 'focus' : loginForm.controls.email.dirty}">
                <label for="email_login">E-Mail</label>
                <input type="email" formControlName="email" [(ngModel)]="user.email" name="email">
                <div class="message text-center">
                  <p>This field is required</p>
                </div>
                <div class="pattern text-center">
                  <p>Enter a valid email.</p>
                </div>
              </div>
              <div class="login-field" [ngClass]="{'error' : loginForm.controls.password.pristine && loginForm.controls.password.touched, 'focus' : loginForm.controls.password.dirty}">
                <label for="pass_login">Password</label>
                <input type="password" [(ngModel)]="user.password" name="password" formControlName="password">
                <div class="message text-center">
                  <p>This field is required</p>
                </div>
              </div>
              <p class="text-center bottom-msg-login">Don't have an account yet? Download the app für Android or iOS, <br>sign in and create your wedding!</p>
              <button class="submit" type="submit" name="couple" [disabled]="!loginForm.valid">Login</button>
            </div>
          </form>
          <div class="wrapper-social-login">
            <div id="google_login" (click)="googleLogin(login)"></div>
            <div id="facebook_login" (click)="facebookLogin()"></div>
          </div>
        </ng-template>
      </ngb-tab>
      <ngb-tab title="Guests">
        <ng-template ngbTabContent>
          <div class="modal-header">
            <h4 class="modal-title">Guest</h4>
          </div>
          <div id="guest_login_form" class="login-form">
            <div class="login-field">
              <label for="email_login">Name</label>
              <input type="text" name="login_name" id="login_name">
              <div class="message text-center">
                <p>This field is required</p>
              </div>
            </div>
            <div class="login-field">
              <label for="pass_login">Wedding Code</label>
              <input type="password" name="login_code" id="login_code">
              <div class="message text-center">
                <p>This field is required</p>
              </div>
              <div class="pattern text-center">
                <p>Enter a valid code.</p>
              </div>
            </div>
            <p class="text-center bottom-msg-login">Also getting married?Take a look at our packages and create <br> your own wedding within the app!</p>
            <button class="submit" id="guest_login_btn" type="button" name="guest">Login</button>
          </div>
        </ng-template>
      </ngb-tab>
    </ngb-tabset>
  </div>
</ng-template>
7个回答

13

您可以使用ViewChild:

在您的ts文件中:

@ViewChild('closeModal') closeModal: ElementRef


@Component({
  ...
})
export class NameComponent extends TicketActionsModal {

  @ViewChild('closeModal') closeModal: ElementRef

  ...

}

当您需要关闭模态框时,可以调用:this.closeModal.nativeElement.click()

例如:

public googleLogin(content): void {
   this.auth.googleAuth().then((res: any) => {
      // close the modal in this moment.
      this.closeModal.nativeElement.click() //<-- here
      const user = res.user;
      this.router.navigate(['/gallery']);
   });
}
在您的html中,将#closeModal添加到按钮:
<button #closeModal type="button" class="close" aria-label="Close" (click)="d('Cross click')">
    <span aria-hidden="true">&times;</span>
</button>

我遇到了错误 Uncaught (in promise): TypeError: _this.modal.nativeElement is undefined - Miguel Frias
现在我所做的是将 #close 放到按钮上,并使用 @viewChild('close'),同时将 ng-template 保留为 #login,但我仍然得到相同的错误 Uncaught (in promise): TypeError: _this.modal.nativeElement is undefined - Miguel Frias
我正在使用来自Angular Bootstrapng-bootstrap,最新版本是1.0.0 Beta,但我将更改为ngx-bootstrap,以查看是否可以更轻松地完成。 - Miguel Frias
你能否用 .ts 和 .html 创建一个要点摘要? - mickaelw
1
在 Angular 8 中,您需要传递两个参数 @ViewChild('closeModal',{static: false}) closeModal: ElementRef; - abhishek kumar
显示剩余8条评论

11

一个简单的方法是隐藏按钮。

  <button id="openModalButton" [hidden]="true" data-toggle="modal" data- 
   target="#myModal">Open Modal</button>
  <button id="closeModalButton" [hidden]="true" data-toggle="modal"        
   data-target="#myModal" class="btn btn-default"                          
  data-dismiss="modal">Close</button>

myModal应该是模态框的ID名称。 要打开模态框

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

关闭模态框。
document.getElementById("closeModalButton").click();

5
跟着这个步骤走
import { Component, ViewChild } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';

@Component({
  selector: 'demo-modal-child',
  templateUrl: './child.html'
})
export class DemoModalChildComponent {
@ViewChild('childModal') public childModal:ModalDirective;

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

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

    <button type="button" class="btn btn-primary" (click)="showChildModal()">Open child modal</button>
    <div bsModal #childModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
<div class="modal-content">
  <div class="modal-header">
    <h4 class="modal-title pull-left">Child modal</h4>
    <button type="button" class="close pull-right" aria-label="Close" (click)="hideChildModal()">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    I am a child modal, opened from parent component!
  </div>
</div>

ngx-bootstrap链接在这里


在这种情况下,即使不是真正的答案,我也将其标记为答案,因为我正在使用另一个名为ng-bootstrap的Bootstrap模块,来自Angular Bootstraop,但是更改为ngx-bootstrap后,问题得到了解决,所以还是谢谢。 - Miguel Frias

3

给你的关闭按钮一个ID

<button id="ModalClose" type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

然后在您的TypeScript中,您可以使用普通的JS

document.getElementById("ModalClose")?.click();

3
使用 NgbModal 类的 "dismissAll()" 方法来关闭模态框。
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

 constructor(
    private modalService: NgbModal
  )

this.modalService.dismissAll();

2
为按钮添加ID(模态框关闭按钮)。
let elem = document.getElementById('submitBtn');

let evt = new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        view: window
    });

elem.dispatchEvent(evt);

0

您可以使用 (click)="modal.close('Done')" 為按鈕添加功能。

例如:

在 HTML 中:

<ng-template #removeModal let-modal>
<div class="modal-header bg-primary">
    <h6 class="modal-title text-light" 
        id="deleteModalCenterTitle">
        Delete
    </h6>
</div>
<div class="modal-body mx-3">
    Are you sure?
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-danger" data-dismiss="modal"
        (click)="doDelete()">
        Delete
    </button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal"
        (click)="modal.close('Done click')">
        Cancel
    </button>
</div></ng-template>

在你的组件中:
使用以下代码启动你的模态框:this.modalService.open(this.removeModal, { centered: true });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接