如何让 angular2 [innerHtml] 工作 [英] How to get angular2 [innerHtml] to work
问题描述
我不知道我做错了什么,因为没有报告错误.
我有一个组件类
import { Component, OnInit, ViewContainerRef } from '@angular/core';@成分({选择器:'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})导出类 AppComponent 实现 OnInit {testhtml = "<p>Hello world</p>";构造函数(){}}}
在我的模板文件中,我做这样的事情:
<div class="blog-post">[innerHtml]="testhtml"</div>
但这似乎不起作用.还有什么我需要导入的吗?
我正在使用 angular-cli "version": "1.0.0-beta.26",
Angular 使用 {{property}}
进行值的插值.这就是你在 div
中显示纯文本的方式,就像这样
解决方案 1:
{{testhtml}}
但这会写出文本,而不是 HTML.
对于 HTML,您需要绑定到属性
解决方案 2:
<div class="blog-post" [innerHtml]="testhtml"></div>
注意我将 [innerHtml]
移到了 div
标签内.
省略方括号将绑定到属性,因此您需要再次插入
解决方案 3:
<div class="blog-post"innerHtml="{{testhtml}}"></div>
属性绑定(解决方案 2)是首选方法.
I don't know what am doing wrong as no errors are report.
I have a component class
import { Component, OnInit, ViewContainerRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
testhtml = "<p>Hello world</p>";
constructor(){}
}
}
And in my template file, I do something like this:
<div class="blog-post">[innerHtml]="testhtml"</div>
But this doesn't seem to work. Is there something else I need to import?
I am using angular-cli "version": "1.0.0-beta.26",
Angular uses {{property}}
for interpolation of values. That is the way that you would display plain text in your div
, like so
Solution 1:
<div class="blog-post">{{testhtml}}</div>
But that will write out text, not HTML.
For HTML, you will need to bind to the property
Solution 2:
<div class="blog-post" [innerHtml]="testhtml"></div>
Note I moved the [innerHtml]
to inside the div
tag.
Leaving out the square brackets would bind to the attribute, so you would need to interpolate again
Solution 3:
<div class="blog-post" innerHtml="{{testhtml}}"></div>
The property binding (Solution 2) is the preferred method.
这篇关于如何让 angular2 [innerHtml] 工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!