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

℡╲_俬逩灬. 提交于 2019-11-26 21:55:07

问题


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


回答1:


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.




回答2:


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"



来源:https://stackoverflow.com/questions/46217049/angular-2-how-can-i-apply-directives-to-sanitized-html-innerhtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!