2

I'm using ngx-markdown to render my FAQ, in it, I've links to external resource (starting http) and internal stuff (starting with /).

I'd like to pass the angular router to my markedOptionsFactory in order to use it for local resources.

Is there a way to pass angular router in the decorator when importing the module:

imports: [
    [...]
    MarkdownModule.forRoot({
        provide: MarkedOptions,
        useFactory: markedOptionsFactory,
    }),
    [...]
],

FYI, my markedOptionsFactory looks like:

export function markedOptionsFactory(): MarkedOptions {
    const renderer = new MarkedRenderer();

    renderer.link = (href: string, title: string, text: string) => {
        const isLocalLink = /^\//.test(href);
        const target = isLocalLink ? '_self' : '_blank';
        const hrefContent = isLocalLink ? `javascript:router.navigateByUrl('${href}')` : href;

        return `<a href="${hrefContent}" target="${target}">${text}</a>`;
};

    return {
        renderer: renderer,
        [...]
    };
}
Alexandre SIRKO
  • 816
  • 11
  • 22

2 Answers2

1

I did not found direct solution from Angular. I had to create a Custom Event from marked.js and then catch it higher in the DOM tree.

Here some piece of code of my work around:

  • First: trigger event from a link (instead of the default routing behavior)
renderer.link = (href: string, title: string, text: string) => {
  const isLocalLink = /^\//.test(href);

  let hrefContent;
  if (isLocalLink) {
    hrefContent = `javascript:document.dispatchEvent(new CustomEvent('routeTo', {detail: '${href}'})); void(0)`;
  } else {
    hrefContent = href;
  }

  return `<a href="${hrefContent}">${text}</a>`;
};
  • Then: catch that event from highest coponent/module possible with:
this.window.document.addEventListener('routeTo', (e: CustomEvent) => {
  e.preventDefault();
  router.navigateByUrl(e.detail);
}, false);

Be careful with Internet Explorer, you will need a polyfill for Custom Event

Alexandre SIRKO
  • 816
  • 11
  • 22
-1

You can follow this answer hope this helps!

Kais Chrif
  • 134
  • 5