Search code examples
javascriptangulartypescriptangular5angular-pipe

Handle click event of element returned by Pipes with Angular 5


I'm using Ionic 3 with Angular 5 and I want to handle the click event of an element returned by Pipes. I've the following code:

linkify.ts:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'linkify',
})
export class LinkifyPipe implements PipeTransform {
    transform(value: string) {

    return value.replace(/@([a-z0-9_.]+)/gi, "<span class='link'>@$1</span>");
  }
}

post.html:

<ion-card-content>
    <p [innerHTML]="post.content | linkify"></p>
</ion-card-content>

So, when post.content has this content:

Hello, @StackOverflow! I'm @Igor

Turns to:

Hello, <span class='link'>@StackOverflow</span>! I'm <span class='link'>@Igor</span>

However, I want to handle the click event in span element, so, I tried:

return value.replace(/@([a-z0-9_.]+)/gi, "<span class='link' tappable (click)='openPage($1)'>@$1</span>");

But I get the following message on console:

WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).

I've added DomSanitizer on linkify.ts:

return this.sanitizer.bypassSecurityTrustHtml(value.replace(/@([a-z0-9_.]+)/gi, "<span class='link' tappable (click)='openPage($1)'>@$1</span>"));

And I've added too the openPage function in both the post.ts and the linkify.ts (in both to check if event is fired):

openPage(link) {
    console.log(link);
}

But nothing happens. The only thing I noticed is that when I click on the element it receives the class "activated", that is, the Angular is detecting the event, but it is not firing the function.

How can I handle this?


Solution

  • Finnally I found a way to get it work. Kept the Pipe and created a HostListener on my component:

    @HostListener("click", ["$event"])
      onClick(e) {
        if (e.target.classList.contains("link")) console.log(e.target);
      }