Angular: Watch for element changes made to DOM tree
using directive watchDomTree and event (dom-changed)
Published in
2 min readJun 30, 2020
As some of you may know already, withMutationObserver
, you can monitor DOM changes. (FYI, MutationObserver also works in IE11)
Here is Vanilla JS version of how to detect any change in your document.
const observer = new MutationObserver(list => {
console.log(‘mutation list’, list);
});
observer.observe(document.body, {attributes: true, childList: true, subtree: true});
// perform any DOM change action in your page. e.g. show/hide
Let’s now wrap this into an Angular directive.
The key point of it is to fire a CustomEvent from inside a directive, which is a little modified version of the code above.
const observer = new MutationObserver(list => {
const evt = new CustomEvent('dom-changed', {
detail: list, bubbles: true
});
el.dispatchEvent(evt);
});
observer.observe(el, {...});
This is how to use this directive, watchDomChange
.
<div watchDomTree (dom-changed)="handleDomChange($event)"></div>
This is the full code for this directive, followed by a demo.
import { Directive, ElementRef, OnInit} from '@angular/core';