Last active
February 9, 2022 21:21
-
-
Save jkyoutsey/f2dff07f47e57e2ec047207fd9261187 to your computer and use it in GitHub Desktop.
Angular Style Anchors on DOM Change Directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div | |
[myStyleAnchors] | |
[innerHtml]="{{ someSafeHtml }}"> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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