Last active
March 24, 2020 14:12
-
-
Save amirzenoozi/eb826fd40a8130a4135d9204724b7ed4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, ElementRef, HostListener, Input, OnDestroy, OnInit } from '@angular/core'; | |
import { ModalService } from 'modal.service'; | |
@Component({ | |
selector: 'demo-modal', | |
templateUrl: './modal.component.html', | |
styleUrls: [ './modal.component.scss' ] | |
}) | |
export class ModalComponent implements OnInit, OnDestroy { | |
@Input() id: string; | |
@Input() relatedModalID: string; | |
@Input() customClass: string; | |
private readonly element: any; | |
constructor(private modalService: ModalService, private el: ElementRef) { | |
this.element = el.nativeElement; | |
} | |
/** | |
* Close When Click on ESC Keyboard Button | |
* @param event: event | |
*/ | |
@HostListener('document:keyup', [ '$event' ]) | |
handleKeyboardEvent(event: KeyboardEvent) { | |
if (event.key === 'Escape' && document.body.classList.contains('modal-open')) { | |
this.closeModal(); | |
} | |
} | |
ngOnInit(): void { | |
const modal = this; | |
if (!this.id) { | |
console.error('modal must have an id'); | |
return; | |
} | |
document.body.appendChild(this.element); | |
this.element.addEventListener('click', function (e: any) { | |
const self = this; | |
if (e.srcElement.classList.contains('modal-layer')) { | |
modal.closeModal(); | |
if ( modal.relatedModalID ) { | |
self.modalService.open( modal.relatedModalID ); | |
} | |
} | |
}.bind(this) ); | |
this.modalService.add(this); | |
} | |
/** | |
* Call Before Component Destroy | |
* Remove modal From service List and remove Element | |
*/ | |
ngOnDestroy(): void { | |
this.modalService.remove(this.id); | |
this.element.remove(); | |
} | |
/** | |
* Open Modal | |
*/ | |
openModal(): void { | |
this.element.firstChild.classList.add('modal--isopen'); | |
/** Check We Have Scroll or Not **/ | |
const viewHeight = document.scrollingElement.clientHeight; | |
const scrollHeight = document.scrollingElement.scrollHeight; | |
if (scrollHeight > viewHeight) { | |
document.body.classList.add('modal-open'); | |
} else { | |
document.body.classList.add('modal-open-nomargin'); | |
} | |
} | |
/** | |
* Close Modal | |
*/ | |
closeModal(): void { | |
this.element.firstChild.classList.remove('modal--isopen'); | |
document.body.classList.remove('modal-open'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment