-
-
Save hookdump/9af7b39caa95c130918feb5a7e8a028d to your computer and use it in GitHub Desktop.
Angular 4 Markdown Component with Router Navigation.
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 { Component, Input, ViewChild, AfterViewInit, ElementRef } from '@angular/core'; | |
import { Router } from '@angular/router'; | |
import { markdown } from 'markdown'; | |
@Component({ | |
selector: 'markdown', | |
template: `<div [innerHtml]="html" #root></div>` | |
}) | |
export class MarkdownComponent implements AfterViewInit { | |
@ViewChild('root') root: ElementRef; | |
html: string; | |
@Input() | |
set data(value: string) { | |
this.html = markdown.toHTML(value); | |
} | |
constructor(private router: Router) { } | |
ngAfterViewInit() { | |
let links: HTMLAnchorElement[] = this.root.nativeElement.querySelectorAll('a'); | |
links.forEach(el => el.addEventListener('click', event => { | |
if (location.origin === (<any>el).origin) { | |
event.preventDefault(); | |
this.router.navigateByUrl(el.getAttribute('href')); | |
} | |
})); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment