Skip to content

Instantly share code, notes, and snippets.

@ssougnez
Last active October 13, 2021 20:11
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ssougnez/121c77f90cb4e5a0359ade4300d110de to your computer and use it in GitHub Desktop.
import { Directive, ElementRef, Input, OnChanges } from '@angular/core';
import { Router } from '@angular/router';
@Directive({
selector: '[html]',
})
export class HtmlDirective implements OnChanges {
private _uniqueId: string;
@Input()
public html: string;
constructor(private _elementRef: ElementRef, private _router: Router) {}
public ngOnChanges(): void {
if (this.html) {
this._uniqueId ||= [...this._elementRef.nativeElement.attributes].find(
(attr) => attr.name.startsWith('_ngcontent-')
).name;
this._elementRef.nativeElement.innerHTML = this.html;
const descandants = this._elementRef.nativeElement.querySelectorAll('*');
for (const element of descandants) {
element.setAttribute(this._uniqueId, '');
if (element.tagName === 'A') {
const href: string = element.href?.toLowerCase();
if (href?.startsWith(location.origin.toLowerCase())) {
element.addEventListener('click', (e: MouseEvent) => {
this._router.navigate([href.substring(location.origin.length)]);
e.preventDefault();
});
}
}
}
} else {
this._elementRef.nativeElement.innerHTML = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment