Skip to content

Instantly share code, notes, and snippets.

@armanozak
Created May 3, 2020 11:31
Show Gist options
  • Save armanozak/2477e38f55995c52f3b159db9521bfcb to your computer and use it in GitHub Desktop.
Save armanozak/2477e38f55995c52f3b159db9521bfcb to your computer and use it in GitHub Desktop.
[Strategy Pattern with TypeScript - ABP Angular Implementation] DomInsertionService #blog #typescript
import { Injectable } from '@angular/core';
import { ContentStrategy } from '../strategies/content.strategy';
import { generateHash } from '../utils';
@Injectable({ providedIn: 'root' })
export class DomInsertionService {
private readonly inserted = new Set<number>();
insertContent<T extends HTMLScriptElement | HTMLStyleElement>(
contentStrategy: ContentStrategy<T>,
): T {
const hash = generateHash(contentStrategy.content);
if (this.inserted.has(hash)) return;
const element = contentStrategy.insertElement();
this.inserted.add(hash);
return element;
}
removeContent(element: HTMLScriptElement | HTMLStyleElement) {
const hash = generateHash(element.textContent);
this.inserted.delete(hash);
element.parentNode.removeChild(element);
}
has(content: string): boolean {
const hash = generateHash(content);
return this.inserted.has(hash);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment