Angular 2: How can I apply directives to sanitized html/innerhtml

clearfix picture clearfix · Sep 14, 2017 · Viewed 8.5k times · Source

I am working on an application where i am getting responses in html format from a server. I am using the DomSanitizer's bypassSecurityTrustHtml and adding the sanitized html to my component ().

My problem is that a few of the elements in the response contains tags to indicate a link can be buildt from the element eg:

<div thisIsActuallyaLink linkParam1="foo" linkParam2="bar">clickHere</div>

I would like to create a directive that is applied to the innerhtml, but while the html is displayed, it is not compiled with my directive...

If anyone is wondering why converting the html is not done serverside: the response is used in several applications and the links must have different relative urls depending on the application :-(

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Oct 3, 2017

This isn't possible with [innerHTML]="..." at all.
You can compile components at runtime to get components and directives for dynamic HTML.

See How can I use/create dynamic template to compile dynamic Component with Angular 2.0? for more details.