Skip to content Skip to sidebar Skip to footer

Can Angular 2 Parse Links Received From External CMS To Be Resolved As Internal

We are working on a decoupled project with Drupal as our backend and Angular as our front-end. Everything is nearing completion but certain (dynamic, as in created in Drupal) pages

Solution 1:

It's been a while since you posted but I didn't find a solution myself so wanted to create this as a future reference.

We solved this problem by using a Directive that we use on the html like so:

<div [innerHTML]='contentFromCMS' appRouteDirective></div>

The Directive captures all clicks and checks if the target is an tag with a href element. If the href is relative, use the router. If it contains hostname (set your own) it gets the path and uses the router. Otherwise it opens in a new window.

import { Directive, ElementRef, HostListener } from '@angular/core';
import { Router } from '@angular/router';

declare let window: any;
declare let document: any;

@Directive({
  selector: '[appRouteDirective]'
})
export class RouterLinkDirective {
  public hostname = '.hygglo.se'; // The starting dot avoids email links as well

  constructor(private el: ElementRef, private router: Router) {}

  @HostListener('click', ['$event'])
  public onClick(e) {
    const href = e.target.getAttribute('href');
    if (e.target.tagName === 'A' && href) {
      e.preventDefault();
      if (this.isLocalLink(href)) {
        this.router.navigate([this.getPathFromURL(href)]);
      } else {
        window.open(e.target.href);
      }
    }
  }

  public getPathFromURL(url: string) {
    let el = document.createElement('a');
    el.href = url;
    return el.pathname;
  }

  public isLocalLink(uri: string) {
    if (uri && (uri.startsWith('/') || uri.includes(this.hostname))) {
      return true;
    } else {
      return false;
    }
  }
}

Post a Comment for "Can Angular 2 Parse Links Received From External CMS To Be Resolved As Internal"