繁体   English   中英

在 ngx 引导模式中检测 Click 事件

[英]Detect Click event inside ngx bootstrap modal

我已经按照本指南实现了一个 ngx 引导模式 - https://valor-software.com/ngx-bootstrap/#/modals#bs-modal-service 但是当模态打开时,我如何检测模态体内的任何点击事件。 我的应用程序组件中有以下代码。

我已经用 viewChild 试过了,但是当我在打开模式后单击它时总是返回未定义。

应用程序组件 HTML -

<button type="button" class="btn btn-primary" (click)="openModal(template)">Create template modal</button>

<ng-template #template>
  <div class="modal-header">
    <h4 class="modal-title pull-left">Modal</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" #modalBody>
    This is a modal.
  </div>
</ng-template>

应用组件 ts -

import { Component, TemplateRef, OnInit, ViewChild, ElementRef } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal'; 

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  host: {
  '(document:click)': 'closemodal($event)'
  }
})

export class AppComponent mplements OnInit{
  @ViewChild('modalBody', { static : false}) modalBody : ElementRef;
  modalRef: BsModalRef;
  constructor(private modalService: BsModalService) {}

  ngOnInit() {}

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


  closemodal(event : any) {
    if (!this.modalBody.nativeElement.contains(event.target)){
       console.log('clicked in the modal')
    }
  }
}

我不确定直接在模态主体 DOM 中绑定事件处理程序有什么问题。 尝试以下

模板

<button style="margin: 10px" type="button" class="btn btn-success" (click)="openModal(template)">Create template modal</button>

<ng-template #template>
  <div class="modal-header">
    <h4 class="modal-title pull-left">Modal</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">
    <span style="cursor: pointer" (mouseup)="textClick($event)">Some sample text</span>
    <br><br>
    <button type="button" class="btn btn-primary" (click)="onClick($event)">Click me</button>
  </div>
</ng-template>

Controller

export class AppComponent {
  modalRef: BsModalRef;
  constructor(private modalService: BsModalService) {}

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

  textClick(event: any) {
    console.log('text clicked inside modal body');
  }

  onClick(event: any) {
    console.log('button clicked inside modal body');
  }
}

工作示例: Stackblitz

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM