1

I have a function which detect url links with Regex and replace by a span tag.

The replacement works fine, the actual problem is: when I use (click)="myFunction()" on this span, he doesn't compile with the click event, just add on html.

my function:

insertHrefs(content: string): string {
    const links = content.match(/\b(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+/gm);
    const linksReplaced = [];

    // tslint:disable-next-line: forin
    for (const i in links) {
      const link = links[i];
      if (linksReplaced.find(l => l === link)) { continue; }

      content = AppUtils.replaceAll(content, link,
       `<span style="color:#357CFF;" (click)="test()">${link}</span>`
      );
      linksReplaced.push(link);
    }
    return content;
  }

the result: http://prntscr.com/ov8yfc

I need some way to add click event to span tag dynamically.

Bianca Yameê
  • 80
  • 1
  • 6

1 Answers1

0

You need to compile the template into elements you can then add into your DOM, without it the browser isn't going to understand what (click)= is.

You can look at this question to see how it can be done. Do note that the first answer was for Angular 2, and was deprecated by Angular 2.something. Another answer is relevant for Angular 4. I suppose the reason for all of this is that compiling templates (or dynamic components) is not something the Angular team really wants you to do.

You can, of course, not compile anything at all, but instead just add a click event to the span element. You will need to look for the elements in your DOM, and then attach the event handler with elem.addEventListener('click', () => { myFunction() });

zmbq
  • 38,013
  • 14
  • 101
  • 171