0

I have my own, silly Twitter alternative that I use for fun. When a user enters a URL in their comment, I want to make it clickable. I've tried this, and it correctly creates the anchor tag, but the link still isn't clickable.

This finds the URL and creates an anchor tag around it:

  makeLinkWithinCommentClickable(comment: any) {
    const hyperlink = (textContent) =>
      textContent.replace(
        /(https?:\/\/[^\s]+)/g,
        (href) => `<a ng-href="${href}">${href}</a>`
      );

    comment.commentText = hyperlink(comment.commentText);
  }

However, you can see it's just an anchor tag in plain text. How can I make it clickable?

I also tried wrapping the anchor in [code]...[/code], but that produced the same results.

enter image description here

This is Angular, and the HTML looks like this:

span{{comment.commentText}}/span

(The span has correct tags. Can't get it to display here.)

Bob Horn
  • 33,387
  • 34
  • 113
  • 219
  • your problem there is that `comment.commentText` is parsed -elsewhere in the code- as text, not HTML. my best guess is that code elsewhere adds commentText to a html node's textContent instead of a html node's innerHTML – hanshenrik Nov 30 '22 at 01:01
  • just to be clear, your problem is `comment.commentText = HTML;` , maybe there is a `comment.commentHTML` property somewhere? – hanshenrik Nov 30 '22 at 01:03
  • 1
    You must set the `.innerHTML` of an element to set the HTML. If you do `.textContent` (which you appear to be doing now), you won't be setting HTML. – CertainPerformance Nov 30 '22 at 01:04
  • I edited my question to show how I'm setting it within the span. The issue is that the comment isn't JUST the link; it's a comment with a link within it. – Bob Horn Nov 30 '22 at 01:15
  • Check this out: https://www.digitalocean.com/community/tutorials/angular-innerhtml-binding-angular – Jack Nov 30 '22 at 01:46
  • @Jack That looks promising. I just did this, and see the link, but it's still not clickable: ``. Interesting, dev tools shows it's just surrounded by ... and the href is no longer there: https://stackoverflow.com/ – Bob Horn Nov 30 '22 at 01:57
  • Are you sure the a tag has a link? Try opening the element inspector and seeing what the result is – Jack Nov 30 '22 at 02:02
  • Yeah, what I showed in my last comment, at the very end, is what the element inspector shows: stackoverflow.com/ – Bob Horn Nov 30 '22 at 02:05
  • If I console.log `comment.commentText`, I see this: attempt 2: https://stackoverflow.com/. Oh, wait, that was me trying `ng-href`. Let me remove the `ng` part... – Bob Horn Nov 30 '22 at 02:06
  • That worked! If you want to add your answer here, I'll gladly accept. Thank you! – Bob Horn Nov 30 '22 at 02:07

0 Answers0