javascript / expert
Snippet
DOM Lifecycle Event Auditing via Custom ElementRef MutationObserver Directive
Direct DOM monitoring using native MutationObserver encapsulated inside an Angular directive. Running outside Angular change detection loop with NgZone prevents triggering unnecessary change detection cycles.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { Directive, ElementRef, inject, DestroyRef, NgZone } from '@angular/core';@Directive({ selector: '[appDomAudit]', standalone: true })export class DomAuditDirective {private el = inject(ElementRef);private ngZone = inject(NgZone);private destroyRef = inject(DestroyRef);constructor() {this.ngZone.runOutsideAngular(() => {const observer = new MutationObserver(records => console.log('DOM Mutation detected:', records.length));observer.observe(this.el.nativeElement, { childList: true, subtree: true });this.destroyRef.onDestroy(() => observer.disconnect());});}}
angular
Breakdown
1
private ngZone = inject(NgZone);
Injects NgZone to explicitly control whether execution occurs within or outside Angular's event loop.
2
this.ngZone.runOutsideAngular(() => {
Executes DOM listener setup outside Angular zone to prevent triggering Change Detection on every mutation.
3
const observer = new MutationObserver(...)
Instantiates native browser MutationObserver for DOM tree element change monitoring.
4
this.destroyRef.onDestroy(() => observer.disconnect());
Registers lifecycle teardown listener via modern DestroyRef API to avoid memory leaks when directive unmounts.