在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
来关闭模态框。
这样,当模态框按钮被点击时,模态框会显示出来。