5

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 :-(

All Іѕ Vаиітy
  • 24,861
  • 16
  • 87
  • 111
clearfix
  • 467
  • 1
  • 5
  • 10
  • 2
    This isn't possible with `[innerHTML]="..."` at all. You can compile components at runtime to get components and directives for dynamic HTML https://stackoverflow.com/questions/38888008/how-can-i-use-create-dynamic-template-to-compile-dynamic-component-with-angular – Günter Zöchbauer Sep 14 '17 at 10:49
  • I need AoT-compilation for my project. Dynamic component looks promising, but I'm guessing it won't work with AoT? I've decided to parse the html and convert the tags to plain links during 'ngAfterViewInit()' for now (loosing the single-page functionallity of routerLinks). – clearfix Sep 18 '17 at 11:14
  • I don't know the current state. A few months ago was a discussion about that and it looked there are ways to make it work together. Not sure if that improved/worsened since then. The discussion was in Angular Github issues. – Günter Zöchbauer Sep 18 '17 at 11:16
  • I had a closer look at this and it seems it will work with AoT compiler. If you submit this as the answer, I will mark it as correct – clearfix Oct 03 '17 at 09:50

2 Answers2

4

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

Maybe try using Pipe, like this:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({ name: 'safeHTML' })
export class SafeHtml implements PipeTransform {

    constructor(private sanitizer: DomSanitizer) { }

    transform(html: string) {
        return this.sanitizer.bypassSecurityTrustHtml(html)
    }
} 

and than [innerHtml]="htmlExample | safeHTML"

lingthe
  • 599
  • 1
  • 6
  • 14
  • 2
    Thats how the domsanitizer works. It similar to what I am already doing, but it doesn't use angular directives (like routerLink) during compilation, so this doesn't address my question. – clearfix Sep 18 '17 at 11:07