在Angular 7中,与jQuery中的$(element).click()相当的是Angular中的@HostListener('click')。
下面是一个使用Angular事件监听器查找模态框显示的示例代码:
首先,在组件类中,使用ViewChild装饰器来获取模态框的引用:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `
Modal Content
`,
styles: [`
.modal {
display: none;
/* modal styles */
}
`]
})
export class MyComponent {
@ViewChild('modalButton') modalButton: ElementRef;
@ViewChild('modal') modal: ElementRef;
ngAfterViewInit() {
// 在视图初始化后,给模态框按钮添加点击事件监听器
this.modalButton.nativeElement.addEventListener('click', this.openModal.bind(this));
}
openModal() {
// 显示模态框
this.modal.nativeElement.style.display = 'block';
}
closeModal() {
// 关闭模态框
this.modal.nativeElement.style.display = 'none';
}
}
在上面的代码中,我们使用了ViewChild装饰器来获取模态框按钮和模态框本身的引用。然后,在ngAfterViewInit生命周期钩子中,我们使用原生JavaScript的addEventListener方法来给模态框按钮添加点击事件监听器,并将其绑定到openModal方法上。在openModal方法中,我们通过设置模态框的display属性为block来显示模态框。同样地,在closeModal方法中,我们通过设置模态框的display属性为none来关闭模态框。
这样,当模态框按钮被点击时,模态框会显示出来。