1

In my app, I have a mechanism that parses the piece of text before rendering and replaces all the links looking text into the actual links. This works great; however, even if I am linking to internal route the app reloads.

Here is one of the examples.

in the template:

<mat-card-title [innerHtml]="resolveTaskDetailsHtml()"></mat-card-title>

Where the resolving function is:

public resolveTaskDetailsHtml() {
    return HtmlService.autolinkUrls(escapeHtml(this.details));
  }

The outcome of this is the content with replaced url looking strings into actual links. Also, if the link is internal the url is relative to the app. Example:

text http://app.domain/route/123

will be replaced with:

text <a href="/route/123">http://app.domain/route/123</a>

Is it possible to redirect to an internal route with these kinds of generated links? And how?

There is another similar question here Add element with RouterLink dynamically, but it does not look like it was resolved

Shurik Agulyansky
  • 2,607
  • 2
  • 34
  • 76

2 Answers2

0

You should use the routerLink directive instead of href, href will circumvene the single page nature of Angular and completely reload the page, while Angular prefers you to use the Router and it's routerLink.

<a [routerLink]="resolveTaskDetailHtml()">

Where resolveTaskDetailHtml should now return: ['/', 'route', '123']

See RouterLink for more information.

Robin De Schepper
  • 4,942
  • 4
  • 35
  • 56
  • The problem with this solution is that the thinks are part of the text and injected after parsing. At that point they are not evaluated as router link anymore (unless I am missing something) – Shurik Agulyansky Jan 26 '20 at 23:09
0

Add a Directive

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

@Directive({
  selector: '[appInnerLink]'
})
export class InnerLinkDirective {
  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) {
      if (href && !href.startsWith('https:') && !href.startsWith('http:')) {
        e.preventDefault();
        this.router.navigate([href]);
      }
    }
  }
}

Usage

<mat-card-title [innerHtml]="resolveTaskDetailsHtml()" appInnerLink></mat-card-title>
Bob-HL
  • 46
  • 4