bypassSecurityTrustHtml disables anchor tag while displaying html using [innerHtml]

2.7k Views Asked by At

I am using Angular 10. I have a scenario to get html string (value returned by rich text editor) and display it in my Application (using innerHtml). I'll be getting all kinds of styles, like background color, font-color, highlight text, hyperlinks etc.

I am using bypassSecurityTrustHtml via pipes (code is below) so that <styles> tags will be considered.

// sanitizeHtml.pipe.ts

@Pipe({ name: 'keepHtml', pure: false })
export class SanitizeHtmlPipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {
  }

  transform(content) {
    return this.sanitizer.bypassSecurityTrustHtml(content);
  }
}

Now the problem is that when I get hyperlink texts <a href="http://www.someurl.com> click here </a>, these anchor links are not working. So, when I click on the link, it doesn't open the href link.

I've seen solutions like using bypassSecurityTrustResourceUrl. But I cannot use it as I won't be able to parse the url alone from the html content.

I also tried to use both the functions like below as suggested in other SO questions but it doesn't help either..

[innerHtml]="myHtmlContent | keepHtml | keepUrl"

[innerHtml]="myHtmlContent | keepUrl | keepHtml" // tried to reorder the pipe still didn't work

Is there a way to make the anchor tag's href links work while using bypassSecurityTrustHtml function?

Thanks for your time.

1

There are 1 best solutions below

0
On BEST ANSWER

After doing some debugging, I just found that we don't need to sanitize url seperately which is inside html string.

If you are using pipe with bypassSecurityTrustHtml and it doesn't work properly with the anchor tag links, then you would have probably done the same mistake which I did.


Solution

Just remove pure: false from @Pipe({ name: 'keepHtml', pure: false }). By doing so, your pipe will became pure pipe (as pure: true is default value)

Pure pipes will be executed only if it detects a change in the value or parameters passed to the pipe where as impure pipes will be called for every change detection cycle.