【发布时间】:2018-10-13 10:29:22
【问题描述】:
我正在尝试在控制器中使用带有花括号的 HTML 模板。
我发现的问题是,当我将 innerHTML 与 safePipe 一起使用时,我看到的是花括号而不是结果。
home.html(模板)
<ul>
<li *ngFor="let item of events">
{{item.name}}
</li>
</ul>
sanitizing.ts
@Pipe({name: 'safe'})
export class SafePipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
default: throw new Error(`Invalid safe type specified: ${type}`);
}
}
}
home.component.html
<div [innerHtml]="myTemplate | safe: 'html'"></div>
结果
{{item.name}}
想要的结果
dummy
【问题讨论】:
-
myTemplate包含什么 -
home.html的内容,我用
return this._http.get ('./ assets / tpl / home.html')得到了 -
@GabrielSule 你不能像在 Angular 1.x 中使用
ng-include指令那样做。 -
@Serginho 除了你给我的答案,有没有办法插入模板和花括号返回数据?
-
不,编译器的工作方式不同,关于它。模板在哪里读取要展开的变量?没有关联的类组件。
标签: javascript angular innerhtml