未加载angular 4中的InnerHTML
我正在研究@angular/core@4.4.6, 这是我的html组件未加载angular 4中的InnerHTML,html,angular,angular-template,Html,Angular,Angular Template,我正在研究@angular/core@4.4.6, 这是我的html组件 <div class="contact" [innerHTML]="template"> 这是我的组件ts代码 this.template = '<div> hello world </div>'; console.log(self.template ); this.template='hello world'; console.log(self.template); 当组件t
<div class="contact" [innerHTML]="template">
这是我的组件ts代码
this.template = '<div> hello world </div>';
console.log(self.template );
this.template='hello world';
console.log(self.template);
当组件ts代码运行时,控制台可以打印出hello world,但是这个html会自动加载到组件中,html页面上的仍然是空的
这是为什么?如何修复?围绕代码片段添加一些上下文会很有帮助。它在类中的声明方式、初始化发生在何处、它是否公开为类的公共成员等都是相关的 然而,我的猜测是Angular不相信HTML是“安全的” 出于我的需要,我必须创建一个管道来处理将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';
}
}
}
有关更多信息,请参阅Angular docs,或在代码注释中找到其他SO帖子的链接。将您的代码更新到此位置,然后重试
self.template = '<div> hello world </div>';
self.template='hello world';
如果它不起作用或您仍在遭受痛苦,请尝试以下jQuery代码(在Angular2中,这不是推荐的方法)
HTML:
TS:
$(“#模板”).html('hello world')代码>您为什么使用self
而不是此
?这可能就是原因[innerHTML]=“template”
指的是此.template
,而不是self.template
。尝试放置self.template='hello world'在组件类的构造函数中输入code>并查看它是否工作。显示组件的完整代码