0

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.

3
  • I'm pretty sure this awkward idea of yours would probably work if you'd define your RouterModule to work with useHash: true, and have your <a href="#your-route"> but it all looks like you're hacking your way inside an angular application. what are you trying to achieve ? why is there a need to use dynamic HTML and not have angular do the heavy lifting ? Commented Nov 2, 2018 at 16:27
  • have you tried using a pipe instead of directly calling sanitizer? See this demo Commented Nov 5, 2018 at 4:12
  • @Stavm, I agree that this is hacking and we are not intending to proceed like this longterm. I was just looking for a simple temporary hack :) Commented Nov 5, 2018 at 13:21

1 Answer 1

1

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:

component1.ts

<div class="comp-1">
  <ng-content></ng-content>
</div>

component2.ts

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

Will render

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

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.