Search code examples
angularangular2-templateangular2-formsangular2-directives

Modal closing when clicking outside it - needs to call same function as when clicked on close modal button in Angular 2


Modal gets closed when clicked on the close modal button as well as when mouse clicked outside the modal I want to call the same function that I call when I click on the close modal button also when I click outside the modal. I am not sure how to do this in Angular 2. Could you please share your ideas on this. Also my Modal is a part of my main html and it doesnot have a separate component or html... Thanks

import { Component, OnInit, NgModule, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core';
import * as jQuery from 'jquery';

export class Component implements OnInit {

  @ViewChild('newModal') newModal: ElementRef; 

public OpenModal(){
jQuery(this.newModal.nativeElement).modal('show');
}
public CloseModal(){
Includes actions taken when close modal button is clicked - I want the same function to be called with I click outside the model
}        
}

I tried the below in html but this is running whenever I click anywhere on the component other than the modal area.

(clickOutside)="CloseModal()"; 

Solution

  • I solved it by adding a function for clicking outside the native element and change in some of the conditions and it worked for me....