简体   繁体   English

如何将点击事件附加到 Angular 7+ 中的插件添加到 DOM 的元素?

[英]How can I attach a click event to an element added to the DOM by a plugin in Angular 7+?

I'm using the VMWareClarity module to add a datagrid to a page.我正在使用 VMWareClarity 模块将数据网格添加到页面。 As part of this datagrid, there's a button to open a popup over the grid to select which columns to hide/show.作为此数据网格的一部分,有一个按钮可以在网格上打开一个弹出窗口,显示 select 要隐藏/显示哪些列。 Once the columns are selected, the popup can be closed by clicking the close button.选择列后,可以通过单击关闭按钮关闭弹出窗口。

I need to attach an action to the close button in the popup, but I haven't been able to access the element to click it as it's only rendered in the DOM once I click the Hide/Show columns button.我需要在弹出窗口中的关闭按钮上附加一个操作,但我无法访问该元素以单击它,因为它仅在单击“隐藏/显示列”按钮后才呈现在 DOM 中。 I've tried adding an elementRef.nativeElement.querySelector in ngAfterViewInit , changeDetection , and @HostListener but none are able to find the new popup element loaded into the DOM.我尝试在ngAfterViewInitchangeDetection@HostListener添加elementRef.nativeElement.querySelector ,但没有一个能够找到加载到 DOM 中的新弹出元素。

Have you checked your parent nodes for your target element?您是否检查了目标元素的父节点? Usually a Pop-up (depends on your UI framework) is created on the hightest DOM Level in the Body Tag.通常一个弹出窗口(取决于您的 UI 框架)是在Body Tag 中的最高 DOM 级别上创建的。 Otherwise you still can implement an Output() EventEmitter like shown here: https://ultimatecourses.com/blog/component-events-event-emitter-output-angular-2否则,您仍然可以实现Output() EventEmitter ,如下所示: https://ultimatecourses.com/blog/component-events-event-emitter-output-angular-2

Example code for the outputting component:输出组件的示例代码:

@Output() change = new EventEmitter<number>();

In this case I was able to use a HostListener on the document, then track if the event target nodeName was the element I was looking for (as every element has a nodeName ):在这种情况下,我可以在文档上使用 HostListener,然后跟踪事件目标nodeName是我正在寻找的元素(因为每个元素都有一个nodeName ):

@HostListener('document:click', ['$event'])
onClick(event) {
    if (event.target.nodeName === 'CLR-ICON') {
      // Do something
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM