Skip to content

Instantly share code, notes, and snippets.

@jkyoutsey
Last active February 9, 2022 21:21
Show Gist options
  • Save jkyoutsey/f2dff07f47e57e2ec047207fd9261187 to your computer and use it in GitHub Desktop.
Save jkyoutsey/f2dff07f47e57e2ec047207fd9261187 to your computer and use it in GitHub Desktop.
Angular Style Anchors on DOM Change Directive
<div
[myStyleAnchors]
[innerHtml]="{{ someSafeHtml }}">
</div>
const renderer = { addClass: (element: any, selector: string) => {} };
const addClassSpy = spyOn(renderer, 'addClass');
const querySelectorSpy = spyOn(el.nativeElement, 'querySelectorAll').and.callThrough();
const mockMutationObserver = jasmine.createSpyObj('mo', ['observe', 'disconnect']);
const directive = new ContentAnchorsDirective(el, renderer as Renderer2);
directive['observer'] = mockMutationObserver;
import { AfterViewInit, Directive, ElementRef, OnDestroy, Renderer2 } from '@angular/core';
@Directive({
selector: '[myStyleAnchors]'
})
export class StyleAnchorsDirective implements AfterViewInit, OnDestroy {
private processing = false;
private observer = new MutationObserver(() => this.styleAnchors());
constructor(private el: ElementRef, private renderer: Renderer2) {}
ngAfterViewInit(): void {
this.styleAnchors();
this.registerListenerForDomChanges();
}
ngOnDestroy() {
this.observer.disconnect();
}
private styleAnchors() {
if (!this.processing) {
this.processing = true;
const anchors = this.el.nativeElement.querySelectorAll('a');
anchors.forEach(a => this.renderer.addClass(a, 'my-cool-class'));
this.processing = false;
}
}
private registerListenerForDomChanges() {
const attributes = false;
const childList = true;
const subtree = true;
this.observer.observe(this.el.nativeElement, { attributes, childList, subtree });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment