简体   繁体   English

Angular 4+:是否可以将输入到模板的字符串评估为HTML?

[英]Angular 4+ : is it possible to evaluate a string input to a template as HTML?

Is there a way to evaluate strings passed into a component's template as HTML? 有没有一种方法可以评估作为HTML传递到组件模板的字符串?

I am passing this: 我通过了:

export const BARS: Blurb = {
  title: "Bars",
  description: "blah blah blah. <a routerLink='/barcades'>Barcades</a>"
}

into this: 到这个:

<h3>{{blurb.title}}</h3>
<p>{{blurb.description}}</p>

It is currently printing <a routerLink='/barcades'>Barcades</a> literally, without evaluating it. 目前,它正在<a routerLink='/barcades'>Barcades</a>字面意思打印<a routerLink='/barcades'>Barcades</a> ,而没有对其进行评估。

As a background, I am making a travel blog. 作为背景,我正在制作旅游博客。 All of my pages have the same structure: a bunch of sections of text with headings. 我所有的页面都有相同的结构:一堆带有标题的文本部分。 In order to avoid code duplication, I created data classes based on a model class like these . 为了避免代码重复,我基于此类的模型类创建了数据类。

Basically, I created JSONs of all of the literary content for my website, then passed them into multiple instances of a common component. 基本上,我为网站创建了所有文学内容的JSON,然后将它们传递到一个公共组件的多个实例中。 This seemed like a great idea at the time, but now I want to add links(preferably even routerLinks). 当时这似乎是个好主意,但现在我想添加链接(最好甚至添加routerLinks)。 Is this possible? 这可能吗? Maybe using pipes? 也许使用管道? And is this even an acceptable strategy? 这甚至是可以接受的策略吗? I'm curious to know if there's a standard approach in Angular. 我很想知道Angular中是否有标准方法。

What you are looking for is innerHTML property. 您正在寻找的是innerHTML属性。 Something like this: <div [innerHTML]="yourStringObject"> .... 诸如此类: <div [innerHTML]="yourStringObject"> ....

You might also need to sanitize it first, look at the thread here . 您可能还需要先对其进行清理,在此处查看线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM