2

I cannot hand-code the <a> ... </a> since the input is a not known string.

I came up with this:

HTMLFormattingService:

makeLinksClickable(inp: string): string {
    const regex = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/ig
    return inp.replace(regex, '<a href="$1" target="_blank">$1</a>');
}

HTML:

<div>
     {{myObject ? this.myService.makeLinksClickable(myObject.text) : ""}}
</div>

The replacing works, but the <a> ... </a> is NOT clickable with this method! That is because <a> not treated as a HTML element but just as text. So the users see the <a> and </a> and cannot click the link.

How can I fix this?

mathematics-and-caffeine
  • 1,664
  • 2
  • 15
  • 19
  • 1
    Does this answer your question? [Angular HTML binding](https://stackoverflow.com/questions/31548311/angular-html-binding) – pkExec Dec 15 '22 at 21:03
  • Also see `linkifyjs` https://linkify.js.org/docs/linkify-string.html – Jacob Dec 15 '22 at 21:35
  • https://stackoverflow.com/questions/71220617/angular-12-d3-tree-displaying-a-routerlink/71390852#71390852 – Eliseo Dec 16 '22 at 08:19

2 Answers2

3

Keep it simple?

<div [innerHTML]="myObject ? this.myService.makeLinksClickable(myObject.text) : ''">
</div>
Anton Marinenko
  • 2,749
  • 1
  • 10
  • 16
0

Try setting the innerHtml of the relevant element:

document.getElementById("myDiv").innerHTML=makeLinksClickable(myUrl);

mancini0
  • 4,285
  • 1
  • 29
  • 31