Dynamically adding html/JS

Maybe I am approaching this the wrong way, but I am have a string with hastags. For example:

This is a comment #coolcomment #hashtag

I need to replace the hashtags with clickable links to navigate to a search. I already know what hashtags the string contains. I originally tried this:

let comment = post.comment;

post.tags.forEach(tag => {
  comment = this.replaceAll(comment, '#' + tag.name, '<span class="tags" (click)="openSearchTag(tag.name)">#' + tag.name + '</span>');

return this.sanitizer.bypassSecurityTrustHtml(comment);

But I am guessing whatever renders the HTML template isn’t rendering the new javascript event added. Not sure what the solution is here. I am sure I need to rethink it completely but open for suggestions.

The HTML is just:<div [innerHTML]="comment"> </div>

and I do:

  ngOnInit() {
    this.comment = this.showPostComment(this.post)
1 Like

If you don’t get any answers you like better, here is my strategy for dealing with a similar situation that completely avoids innerHTML.


@mikelbring No you’re right, the html template won’t render the new js at once, but you can use async in any load of js libraries.

Hope it helps,

Thanks for the replies. Maybe a cop out, but I ended up just using jquery. Seems to work great, it’s a really tiny feature so I am not to worried about it.