javascript - 在 ngx 引导模式中检测 Click 事件
问题描述
我已经按照本指南实施了一个 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">×</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">×</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>
控制器
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
推荐阅读
- swift - 在 Vapor 中手动创建 SQLite 数据库中的数据
- python-3.x - 应用维纳滤波器使用 python 去除噪声
- php - 来自不同类的电子邮件验证函数似乎返回了错误的值
- authorization - 通过 XACML 策略的 RBAC/ABAC
- java - 实现一个函数来检查一个链表是否是回文 - 没有递归,没有堆栈,没有反向
- sql - 基于优先级的数据行 SQL 优化
- uiviewcontroller - 应用程序未使用 AppDelegate 启动,didFinishLaunchingWithOptions() 永远不会被调用
- javascript - 缩略图滑块显示视频和图像
- google-api - 从 Google+ API 迁移 Google Sign-In auth2(浏览器弹出窗口)
- maven - 从 netbeans maven webapp 中的实体类生成 RESTful Webservices 导致应用程序失败,显示“Payara Server, deploy, null, false”