0

I'm building a content system where I want users to be able to create a post with a block of text. If they use the '#' symbol, I add it to my database. Then in my front end, I show the text when a visitor comes.

I want to be able to parse out all of the #'s and pass them through the routeLink to search for all posts that have a matching #.

This is all working with one exception. When I pass in my text to the user with:

 LinkAllHashes(t: string){
    this.bodyText = t.replace(/(^|\s)(#[a-zA-Z\d][\w-]*)/ig, "$1<span (click)='SearchAllHashes($2)' class='hash_tag'>$2</span>");

Everything works but it ignores the (click) event. I've been reading all over the place and it appears that I can't attach a function inside of an innerHtml at runtime. Is this so? How can I get around this?

If I simply do this:

 PipeAllHashes(t: string){
   this.comcom = t.replace(/(^|\s)(#[a-zA-Z\d][\w-]*)/ig, "$1<a href='search-results/$2)' class='hash_tag'>$2</a>");

It works but then it reloads the page and is terrible for user experience. This is why I need to use routeLink.

Any ideas?

*UPDATE

So after much banging my head against the wall I've decided that my current method is best case (pending a better solution).

  1. get the string.
  2. replace the string #*'s with a
  3. use innerHtml

I'm basing this on this screenshot from a random tweet I inspected.

Screenshot of the tweet with a #

Any better ideas and I'm all ears.

DKinnison
  • 355
  • 1
  • 3
  • 16
  • This sounds like a bad idea for multiple reasons (writing frontend in two places, security reasons, ...) But if I had to do that, I would disable sanitizing (angular does that in innerHTML by default and then execute a script on native JS-DOM-click, calling a service in your app – Phil Nov 09 '17 at 21:26
  • I want to avoid disabling sanitizing. And I want to avoid code injection or service manipulation. So if you had a string of text with some #hashtags thrown in, how could you dynamically make them link to a different page? My design doesn't have a way to display the tags in their own area. I see how that would be easy as I would just ngFor each of them and add them to a list with the function I wanted but I want to keep this in the text like twitter has it. – DKinnison Nov 09 '17 at 21:40
  • So upon further inspection. I went into twitter and it seems that when you click on a #, it takes you to a new view within their app. This view populates the search bar and runs the search. So if you're on Android, you can back up through your results because it's making a new page each time. HOWEVER, in YouTube, I can't tell if it's the case. Either they are using their routeLink or they are reloading the site SUPER fast. – DKinnison Nov 09 '17 at 22:37
  • I have no idea, maybe use @Hotlistener ('mouseDown')? – Eliseo Nov 10 '17 at 07:49

0 Answers0