如何使angular2 [innerHtml]工作

Lea*_*day 22 angular

因为没有错误报告,我不知道出了什么问题.

我有一个组件类

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(){}

 }

}
Run Code Online (Sandbox Code Playgroud)

在我的模板文件中,我做了这样的事情:

<div class="blog-post">[innerHtml]="testhtml"</div>
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用.我还需要输入其他东西吗?

我正在使用angular-cli"版本":"1.0.0-beta.26",

Cob*_*ger 53

角度{{property}}用于插值.这就是你在自己中显示纯文本的方式div,就像这样

解决方案1:

<div class="blog-post">{{testhtml}}</div>
Run Code Online (Sandbox Code Playgroud)

但那会写出文字,而不是HTML.

对于HTML,您需要绑定到该属性

解决方案2:

<div class="blog-post" [innerHtml]="testhtml"></div>
Run Code Online (Sandbox Code Playgroud)

注意我移动[innerHtml]div标签内部.

省略方括号将绑定到属性,因此您需要再次插值

解决方案3:

<div class="blog-post" innerHtml="{{testhtml}}"></div>
Run Code Online (Sandbox Code Playgroud)

属性绑定(解决方案2)是首选方法.


Pad*_*dhu 6

您必须像这样在标记内添加属性。

<div class="blog-post" [innerHtml]="testhtml"></div>
Run Code Online (Sandbox Code Playgroud)