[英]What is the best practice to listening to DOM event in Angular 8?
[英]Angular - Listening for a specific DOM insertion, then listen for scroll event
假設這是一個小部件元素的 HTML:
<div class = "a b">
<div class = "c d e">
</div>
</div>
我想聽那個被添加到 DOM 的小部件(最好通過 html 類來捕捉它)。 當它被添加時,我想監聽一個滾動事件(鼠標滾輪或下拉滾動器),這樣當用戶滾動時,小部件就會從 DOM 中刪除。
我聽說過各種實現,包括使用document.queryselector()
、 @HostListener
、事件發射器、 ngDoCheck
等。我正在尋找一種對性能影響最小的實現,最好都在我的 angular 組件中,我們稱之為我的MyComponent
。
編輯:我正在處理的應用程序是一個大型企業應用程序
編輯 2:我無權訪問小部件的 Angular 組件,這就是為什么我不能使用@ViewChild
,所以我能抓住它的唯一方法是在它被添加到 DOM 時使用它的 class 名稱。 點擊圖標后顯示小部件; 我也找不到圖標的 onclick 事件處理程序。
您可以通過事件委托來做到這一點。 將滾動偵聽器分配給文檔,然后搜索並刪除您的 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.