我正在研究@ angular / core @ 4.4.6,
这是我的组件html
<div class="contact" [innerHTML]="template">
这是我的组件ts代码
this.template = '<div> hello world </div>';
console.log(self.template );
当组件ts代码运行时,控制台可以打印出hello world,但是这个html会自动加载到组件中,html页面上仍然是空的。
为什么会这样以及如何解决?
答案 0 :(得分:1)
您的代码段周围的更多上下文会有所帮助。类似于它在课堂上宣布的方式,这种初始化发生在哪里,是因为该类的公共成员是相关的。
但是,我的猜测是Angular并不信任HTML,因为&#34;安全&#34;。
根据我的需要,我必须创建一个管道来处理绑定HTML标记到模板:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
/**
* See link for more detail: https://stackoverflow.com/questions/39628007/angular2-innerhtml-binding-remove-style-attribute
*/
@Pipe({
name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value: string, args?: any): SafeHtml {
if(value) {
return this.sanitized.bypassSecurityTrustHtml(value);
} else {
return 'Undefined HTML';
}
}
}
请参阅Dom Sanitizer的Angular文档,或按照代码注释中其他SO帖子的链接获取更多信息。
答案 1 :(得分:0)
将您的代码更新为此,然后尝试
self.template = '<div> hello world </div>';
如果它不起作用或者您还在苦苦尝试以下 jQuery 代码(这不是Angular2中的推荐方法)
HTML :<div class="contact" id="template">
TS :$('#template').html('<div> hello world </div>');