如何在我的模板 (Angular2/TypeScript) 中将 HTML 字符串转换为 HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36921180/
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-10-21 03:26:58  来源:igfitidea点击:

How can I convert strings of HTML into HTML in my template (Angular2/TypeScript)?

javascripttemplatestypescriptangularecmascript-6

提问by McPhelpsius

I have this object in a dummy-data.tsfile. Through a service I pull it successfully in to app.component.ts.

我在一个dummy-data.ts文件中有这个对象。通过一项服务,我成功地将其拉入到app.component.ts.

{name:"Object1", 
    prop1: {key:'value', key:'value'},
    password: "P@ssword1",
    htmlText:'<h4>This is THE demo text</h4><p>I want it to display as HTML</p>'
}

Currently app.component.tslooks like this, to start out simply:

目前app.component.ts看起来像这样,简单地开始:

@Component({
    selector: 'my-app',
    template: `<h1>{{title}}</h1>
        <p *ngFor="#plot of plots">
            {{plot.personalPanelText.transition}}
        </p>
`,
providers: [PlotService]  
})

The end result is strings instead of HTML. I want the HTML to be code, not text with HTML tags.

最终结果是字符串而不是 HTML。我希望 HTML 是代码,而不是带有 HTML 标签的文本。

I've tried a couple ways and poked around the world wide nets and Angular2 docs, but couldn't find a solution.

我尝试了几种方法,并在全球范围内浏览了网络和 Angular2 文档,但找不到解决方案。

Thanks in advance!

提前致谢!

回答by Günter Z?chbauer

You can bind to innerHtmllike:

你可以绑定innerHtml喜欢:

<div [innerHtml]="someProp.htmlText"></div>

Angular does not instantiate any components where the selectors that match tags or attributes in HTML added this way nor will it resolve any bindings (like {{xx}})

Angular 不会实例化与 HTML 中的标签或属性相匹配的选择器以这种方式添加的任何组件,也不会解析任何绑定(如{{xx}}

See also How to bind raw html in Angular2

另请参阅如何在 Angular2 中绑定原始 html