Angular – how to make angular parse sanitized html


In my component template I have code that looks like this:

  <div [innerHtml]='sanitizedHtml'></div>

In the component declaration:

let unsafeHtml = '<a routerLink="/some-other-page"> Link </a>';
this.sanitizedHtml = sanitizer.bypassSecurityTrustHtml(unsafeHtml);

Inspecting HTML content in the rendered page I can see the DOM generated, but when I click on the link, nothing happens. I expect, that angular ignored the routerLink directive and did nothing with it.

Any way to work around this?

I could change routerLink to simple href, but in the latter case browser performs the whole page reload, whereas I want to navigate within my angular application.


Putting HTML into the strings within TS is very bad design.
How should Angular know if any string may contain unsafe HTML without evaluating each and every one? It would be pretty mad.

Internally, Angular CLI is running file watchers on all files but they jobs behind are very different. Also much of the actual output markup will be manipulated, as angular resolves nested elements and scope css. It does not always render the actual page, which would be necessary here, to find out there is a directed hidden in some TS file.

The “Angular way” basically forbids you to use innerHTML directive.
You can use ng-content to project html into another component:


<div class="comp-1">


  <a routerLink="..."></a>

Will render

<div class="comp-1">
  <a routerLink="..."></a>

But this assumes you can translate your static string markup into components. However also the only way I think is even possible without writing a custom preprocessor.

Answered By – mchl18

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.