【发布时间】:2017-12-11 05:53:34
【问题描述】:
这是我第一次在 Angular 上使用 typescript。我一直在努力创建这个模态指令,灵感来自ngMorph。
这按预期工作正常,但我遇到了一个非常奇怪的问题。当我单击按钮打开模态框时,它工作得很好,我关闭模态框,它就关闭了。当我尝试再次打开同一个模态框并尝试关闭时,它不会关闭。而且它也不会抛出任何错误。
调试后发现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 来关闭模态对话框。 -
对不起,那是我的错误,当我更改实际的班级名称时,我忘记了这一点。当我第一次打开它时,我的模式一切正常,但是当我第二次打开模式时,我无法关闭它。
modal-active没有被删除,尽管我有一个切换类closeElement.addEventListener的功能
标签: javascript angular angularjs-directive angular5