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

10.6k views Asked by At

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

2

There are 2 answers

0
Günter Zöchbauer On BEST ANSWER

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.

1
lingthe On

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"