使用 *ngfor对象变量显示自定义HTML元素
我有一个界面:
export interface Project {
id: number;
name: string;
description: string;
previewHTMLElement: string;
}
我在列表中使用:
export const PROJECTLIST: Project[] = [
{id: 1, name: 'a-cool-name', description: 'a cute description', previewHTMLElement: '<img src="assets/images/{{project.name}}.png">'}
]
我试图在NGFOR指令中使用:
<div *ngFor="let project of projectList">
{{project.previewHTMLElement}}
</div>
但这只是替换 {{project.previewhtmlelement}}}}
用#Text block重复任何内容在字符串中。我需要能够将任何类型的元素放在字符串中,并将其作为实际的htmlemlement呈现。
使用角指令实现这一目标的正确方法是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Angular 2+支持
[InnerHTML]
属性绑定将呈现HTML。如果您否则要使用插值,它将被视为字符串。我不相信InnerHTML不首先清洁的任何东西。因此,使用Domsanitizer,Angular的服务有助于防止攻击者将恶意客户端脚本注入网页,通常称为跨站点脚本或XSS。
消毒管的
工作示例:
Angular 2+ supports an
[innerHTML]
property binding that will render HTML. If you were to otherwise use interpolation, it would be treated as a string.I wouldn't trust anything to be used with innerHTML without cleaning it first. So, with DomSanitizer, a service of Angular helps to prevent attackers from injecting malicious client-side scripts into web pages, which is often referred to as Cross-site Scripting or XSS.
The sanitizer pipe
Working example: https://stackblitz.com/edit/angular-pqwwes?file=app%2Fapp.component.html
有多种方法可以做到这一点,有些比其他方法更有趣/推荐。
您正在尝试的方法是行不通的,因为插值将以字符串的形式打印出来...您可以将InnerHTML属性用作将IMG标签作为DIV的孩子附加的一种方式,但这被认为是安全风险。
另一种方法是在ng-template标签中创建多个模板,使用适用于用例的正确元素,并选择其中一个呈现动态渲染,将当前的ngfor元素传递为上下文变量(本文可以帮助您了解如何实现这一目标)!
干杯!
There are multiple ways to do this, some more interesting/recomended than others.
What you are trying wouldn't work, because interpolation will print stuff as a string...you could use the innerHTML property as a way to append the img tag as a child of your div, but this is considered a security risk.
Another way to do it is creating multiple templates within ng-template tags, using the correct elements for your use case and choosing one of them to render dynamically, passing the current ngFor element as a context variable (this article can help you understand how to achieve this)!
Cheers!