检测ngx引导程序模式内的Click事件

问题描述 投票:0回答:1

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

我已经尝试过使用viewChild进行此操作,但是在打开模态后在模态内部单击时,总是返回undefined。

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

App Component 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')
    }
  }
}
javascript angular ngx-bootstrap
1个回答
0
投票

我不确定直接在模式主体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>

控制器

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

© www.soinside.com 2019 - 2024. All rights reserved.