angular 4 中的 InnerHTML 未加载
InnerHTML in angular 4 is not loaded
我正在开发@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页面上的还是空。
这是为什么以及如何解决?
关于您的代码片段的更多上下文会有所帮助。诸如它在 class 中的声明方式、此初始化发生在哪里、它是否作为 class 的 public 成员公开之类的事情是相关的。
但是,我的猜测是 Angular 不信任 HTML 作为 "safe"。
为了我的需要,我必须创建一个管道来处理绑定 HTML 标记到模板:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
/**
* See link for more detail:
*/
@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 文档或在代码注释中按照 link 到另一个 SO post 了解更多信息。
更新您的代码并尝试,
self.template = '<div> hello world </div>';
如果它不起作用或者您仍然在受苦,请尝试以下 jQuery 代码(这在 Angular2 中不推荐)
HTML: <div class="contact" id="template">
TS: $('#template').html('<div> hello world </div>');
我正在开发@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页面上的还是空。
这是为什么以及如何解决?
关于您的代码片段的更多上下文会有所帮助。诸如它在 class 中的声明方式、此初始化发生在哪里、它是否作为 class 的 public 成员公开之类的事情是相关的。
但是,我的猜测是 Angular 不信任 HTML 作为 "safe"。
为了我的需要,我必须创建一个管道来处理绑定 HTML 标记到模板:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
/**
* See link for more detail:
*/
@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 文档或在代码注释中按照 link 到另一个 SO post 了解更多信息。
更新您的代码并尝试,
self.template = '<div> hello world </div>';
如果它不起作用或者您仍然在受苦,请尝试以下 jQuery 代码(这在 Angular2 中不推荐)
HTML: <div class="contact" id="template">
TS: $('#template').html('<div> hello world </div>');