これは、まずはtypescriptを使用してAngularで初めてです。私は実際にngMorphからインスパイアされたこのモーダルディレクティブを作成しようと努力してきました。angular5 - モーダルディレクティブ
これは正常に動作していますが、非常に奇妙な問題が発生しています。ボタンをクリックしてモーダルボックスを開くと、それは正常に機能し、モーダルボックスを閉じると閉じます。同じモーダルボックスを再度開いて閉じようとすると、閉じません。そして、それはどんなエラーも投げません。
デバッグ後、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を使用せずに角を作っています。どんな助けもありがとう。
'data-modal =" edit-sample-modal "'これはあなたが対象とするIDではないことがわかっている場合です。ターゲット要素のIDは 'edit-item-modal'です。 hostlistenerを使用してモーダルダイアログを閉じることもできます。 – Jai
申し訳ありませんが、私の間違いでした。実際のクラス名を変更していたとき、私はそれを忘れていました。私のモーダルは、初めて開いたときにうまくいきますが、モーダルを開くともう一度閉じることができません。 'closeElement.addEventListener'クラスを切り替える機能はありますが、' modal-active'は削除されません。 –