이것은 타이 스크립트를 사용하여 Angular에서 처음입니다. 나는이 모달 지시어를 만들기 위해 열심히 노력해 왔으며, ngMorph에서 영감을 얻었다.angular 5 - 모달 지시문
예상대로 잘 작동하지만 매우 이상한 문제가 발생했습니다. 버튼을 클릭하여 모달 상자를 열면 제대로 작동하고 모달 상자를 닫으면 닫힙니다. 같은 모달 상자를 다시 열어 닫으려고하면 닫히지 않습니다. 그리고 어떤 오류도 발생시키지 않습니다.
디버깅 후 modal-button
의 modal-active
클래스가 제거되지 않는 것을 발견했습니다. HTML
<div class="modal-button edit-sample-modal" [appModal] data-modal="edit-sample-modal">Open Modal</div>
<div class="custom-modal" id="edit-sample-modal">
<a href="javascript:void(0)" class="text-default">
<i class="fa fa-close fa-fw close-modal"></i>
</a>
</div>
다음은 모달
import { Directive, ElementRef, AfterViewChecked, Input, HostListener } from '@angular/core';
@Directive({
selector: '[appModal]'
})
export class ModalDirective implements AfterViewChecked {
@Input()
appModal: string;
constructor(
private element: ElementRef
) { }
ngAfterViewChecked() {
// function to go here
this.initModalBox(this.element.nativeElement, this.element.nativeElement.getAttribute('data-modal'));
}
@HostListener('click') onclick() {
this.initModalBox(this.element.nativeElement, this.element.nativeElement.getAttribute('data-modal'));
const modalElement = document.getElementById(this.element.nativeElement.getAttribute('data-modal'));
this.element.nativeElement.classList.toggle('modal-active');
modalElement.classList.toggle('modal-open');
}
initModalBox(button: HTMLElement, modalDialog: string) {
const trigger: HTMLElement = button;
const triggerPos = trigger.getBoundingClientRect();
const modalElement = document.getElementById(modalDialog);
modalElement.style.top = `${triggerPos.top}px`;
modalElement.style.left = `${triggerPos.left}px`;
modalElement.style.height = `${triggerPos.height}px`;
modalElement.style.width = `${triggerPos.width}px`;
modalElement.style.position = 'fixed';
const closeElement = modalElement.getElementsByClassName('close-modal')[0];
closeElement.addEventListener('click', function() {
modalElement.classList.toggle('modal-open');
// this.element.nativeElement.classList.toggle('modal-active');
document.getElementsByClassName(modalElement.getAttribute('id'))[0].classList.toggle('modal-active');
});
}
}
내가 코드, 난 그냥 일을하지 완벽한 배우고 알고 할 내가 지금까지 함께 왔어요 내 코드입니다 . 심지어 jQuery를 사용하고 싶지만 Angular 프로젝트를 사용하고 싶지 않습니다. jQuery를 사용하지 않고 각진 방식으로 만들려고합니다. 어떤 도움을 주시면 감사하겠습니다.
당신이 타겟팅하는 ID가 아니라면'data-modal = "edit-sample-modal"' 대상 요소의 ID는'edit-item-modal'입니다. hostlistener를 사용하여 모달 대화 상자를 닫을 수도 있습니다. – Jai
죄송합니다. 저의 실수였습니다. 실제 클래스 이름을 변경하면 잊어 버렸습니다. 처음으로 열면 내 모달이 모두 정상적으로 작동하지만 두 번째로 모달을 열면 닫을 수 없습니다. 'closeElement.addEventListener' 클래스를 토글하는 함수가 있지만'modal-active'는 제거되지 않습니다 –