Angular DomSanitizer不绑定角度组件 [英] Angular DomSanitizer not binding angular component
问题描述
我正在尝试将html内容动态添加到DIV中.静态地,这很好.
I am trying to add html content dynamically into a DIV. Statically this works nicely.
有效的代码:
<popover-content #pop1
title="Cool Popover"
placement="right"
[closeOnClickOutside]="true">
Popped up!!!
</popover-content>
<div>
<span>Testing with <span [popover]="pop1" [popoverOnHover]="true">popover</span> as they are not working with DomSanitizer</span>
</div>
现在,我需要在后端中生成此div内容,然后必须在div中动态添加此内容.
Now I need to generate this div content in the backend and then have to dynamically add this inside the div.
无效的代码: HTML:
<popover-content #pop1
title="Cool PopOver"
placement="right"
[closeOnClickOutside]="true">
Popped up!!!
</popover-content>
<div [innerHtml]="message | safeHtml">
</div>
.ts文件:
this.message = '<span>Testing with <span [popover]="pop1" [popoverOnHover]="true">popover</span> as they are not working with DomSanitizer</span>'
管道:
import {Pipe, PipeTransform} from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';
@Pipe({
name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {
}
transform(value) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
在此之后,也没有调用popover组件.
After this also the popover component was not getting called.
在检查时,我确实看到,对于将动态添加的innerHtml
内容添加到DIV中,angular并没有在标签属性中添加某些特殊行为.为什么这样?
我该如何运作呢?
While inspecting, I did see that, for dynamically added innerHtml
content to DIV, angular is not adding some special behavior to the tag attributes. Why so?
And how can I make it work?
推荐答案
使用[innerHTML]="..."
您可以将HTML添加到DOM中,但是Angular并不关心它包含的HTML,除了清理.
With [innerHTML]="..."
you can add HTML to the DOM, but Angular won't care what HTML it contains, except for sanitization.
角度组件,指令,事件和属性绑定仅仅适用于静态添加到组件模板的HTML.
Angular components, directives, event and property bindings only work for HTML added statically to a components template.
What you can do is to compile the HTML with a components template at runtime like explained in How can I use/create dynamic template to compile dynamic Component with Angular 2.0?
这篇关于Angular DomSanitizer不绑定角度组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!