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

2

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

Timbal answered 14/9, 2017 at 10:47 Comment(4)
This isn't possible with [innerHTML]="..." at all. You can compile components at runtime to get components and directives for dynamic HTML #38888508Diedra
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).Timbal
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.Diedra
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 correctTimbal
T
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.

Teraterai answered 3/10, 2017 at 10:26 Comment(0)
T
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"

Tourmaline answered 14/9, 2017 at 10:59 Comment(1)
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.Timbal

© 2022 - 2024 — McMap. All rights reserved.