简体   繁体   English

Angular - 监听特定的 DOM 插入,然后监听滚动事件

[英]Angular - Listening for a specific DOM insertion, then listen for scroll event

Let's say this is the HTML for a widget element:假设这是一个小部件元素的 HTML:

<div class = "a b">
     <div class = "c d e">
     </div>
</div>

I want to listen for that widget being added to the DOM (preferably catch it by html class).我想听那个被添加到 DOM 的小部件(最好通过 html 类来捕捉它)。 And when it is added, I want to listen for a scroll event (mouse-wheel or the drag-down scroller), so that when the user scrolls, the widget is removed from the DOM.当它被添加时,我想监听一个滚动事件(鼠标滚轮或下拉滚动器),这样当用户滚动时,小部件就会从 DOM 中删除。

I've heard of various implementations including using document.queryselector() , @HostListener , Event emitter, ngDoCheck etc. I'm looking for an implementation that has the smallest impact on performance, and preferably all within my angular component, let's call it MyComponent .我听说过各种实现,包括使用document.queryselector()@HostListener 、事件发射器、 ngDoCheck等。我正在寻找一种对性能影响最小的实现,最好都在我的 angular 组件中,我们称之为我的MyComponent

EDIT: The application I'm working on is a large enterprise application编辑:我正在处理的应用程序是一个大型企业应用程序

EDIT 2: I don't have access to the widget's Angular component, that's why I can't use @ViewChild , so the only way I can catch it is by it's class names when it's added to the DOM.编辑 2:我无权访问小部件的 Angular 组件,这就是为什么我不能使用@ViewChild ,所以我能抓住它的唯一方法是在它被添加到 DOM 时使用它的 class 名称。 The widget is displayed after an icon is clicked;点击图标后显示小部件; I haven't been able to find the icon's onclick event handler either.我也找不到图标的 onclick 事件处理程序。

You can do this with event delegation.您可以通过事件委托来做到这一点。 Assign the scroll listener to the document, then search and remove your div if it exists.将滚动侦听器分配给文档,然后搜索并删除您的 div(如果存在)。

 let new_div = document.createElement('div'); new_div.id = 'your_widget'; new_div.style.height = '5000px'; new_div.innerText = "hello"; document.body.appendChild(new_div); document.addEventListener('scroll', (e)=>{ if(document.querySelector('#your_widget')){ document.querySelector('#your_widget').remove(); } })
 <body></body>

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

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