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';
declareletwindow: any;
declareletdocument: any;
@Directive({
selector: '[appRouteDirective]'
})
exportclassRouterLinkDirective {
public hostname = '.hygglo.se'; // The starting dot avoids email links as wellconstructor(private el: ElementRef, private router: Router) {}
@HostListener('click', ['$event'])
publiconClick(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);
}
}
}
publicgetPathFromURL(url: string) {
let el = document.createElement('a');
el.href = url;
return el.pathname;
}
publicisLocalLink(uri: string) {
if (uri && (uri.startsWith('/') || uri.includes(this.hostname))) {
returntrue;
} else {
returnfalse;
}
}
}
Post a Comment for "Can Angular 2 Parse Links Received From External Cms To Be Resolved As Internal"