如何在 Angular 4+ 中使用 html 标签呈现字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49013217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 15:08:46  来源:igfitidea点击:

How to render string with html tags in Angular 4+?

htmlangularrendering

提问by Shams Nahid

In my angular 4 app, I have a string like

在我的 angular 4 应用程序中,我有一个像

comment: string;
comment = "<p><em><strong>abc</strong></em></p>";

When I serve this text in my html, like

当我在我的 html 中提供此文本时,例如

{{comment}}

Then it displays:

然后它显示:

<p><em><strong>abc</strong></em></p>

But I need to display the text "abc" in bold and italic form, like abc

但我需要以粗体和斜体形式显示文本“abc”,如 abc

How can I do this?

我怎样才能做到这一点?

回答by Haifeng Zhang

Use one way flow syntax property binding:

使用一种方式流语法属性绑定

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>tag but keeps safe content such as the <b>element."

来自 angular 文档:“Angular 将值识别为不安全并自动对其进行清理,这会删除<script>标签但保留<b>元素等安全内容。”