0

I want to have something that finds URLs in text and make them clickable. So to achive this I have created a custom pipe:

@Pipe({
  name: 'urlify'
})
export class UrlifyPipe implements PipeTransform {
  transform(text: any): any {
    const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z\d+&@#/%?=~_|!:,.;]*[-A-Z\d+&@#/%=~_|])/ig;

    return text.replace(urlRegex, (url) => {
      return '<a href="' + url + '">' + url + '</a>';
    });
  }
}

And that works as expected when I use it together with <div [innerHtml]="someText | urlify">

But the problem is that in some cases wrapping div is clickable so I have to stopPropagation and preventDefault on <a> element.

So I have created a directive for that:

@Directive({
  selector: '[sfStopPropagation]'
})
export class StopPropagationDirective {
  @HostListener("click", ["$event"])
  public onClick(event: any): void {
    event.preventDefault();
    event.stopPropagation();
  }
}

And than just use this in the pipe return '<a sfStopPropagation href="' + url + '">' + url + '</a>';

The problem is that is not working at all. I even tried to create a method in the pipe file and call it on click for the element but it also doesn't work (the same with ${ }):

enter image description here

And this is an example where I'm using it:

enter image description here

Can someone help me?

D.Zet
  • 753
  • 3
  • 11
  • 32
  • https://stackoverflow.com/questions/71479471/execute-angular-innerhtml-as-normal-angular-code/71480844#71480844 (be sure check also the links in the answer) – Eliseo Jun 06 '22 at 08:52
  • This may not solve your problem, but look like implement `urlify` as component is more suitable than as pipe. – Yong Shun Jun 06 '22 at 08:52

0 Answers0