Reputation: 275
I have implemented a ngx bootstrap modal following this guide - https://valor-software.com/ngx-bootstrap/#/modals#bs-modal-service. but when the modal is opened how can i detect any click events inside the modal body. I have the below code in my app component.
I have tried this with viewChild but when I am clicking inside the modal after it is opened always returns undefined.
App Component 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>
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')
}
}
}
Upvotes: 1
Views: 1811
Reputation: 31105
I am not sure what is the issue with binding a event handler directly in the modal body DOM. Try the following
Template
<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>
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');
}
}
Working example: Stackblitz
Upvotes: 1