问题
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