angular - 如何让 angular2 [innerHtml] 工作

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

 }

}

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

<div class="blog-post">[innerHtml]="testhtml"</div>

但这似乎行不通。我还需要导入其他东西吗?

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

最佳答案

Angular 使用 {{property}} 进行值的插值。这就是您在 div 中显示纯文本的方式,就像这样

解决方案一:

<div class="blog-post">{{testhtml}}</div>

但是那会写出文本,而不是 HTML。

对于 HTML,您需要绑定(bind)到属性

解决方案 2:

<div class="blog-post" [innerHtml]="testhtml"></div>

请注意,我将 [innerHtml] 移到了 div 标签内。

省略方括号会绑定(bind)到属性,因此您需要再次进行插值

解决方案 3:

<div class="blog-post" innerHtml="{{testhtml}}"></div>

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

关于angular - 如何让 angular2 [innerHtml] 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41979458/

相关文章:

javascript - 如何在 "li tag href"中使用for循环

angular - 如何在 Highcharts 点击事件中调用 typescript 功能

angular - 如何在 angular 2 中动态设置 index.html 中的 Google map 键?

具有适当子条目的 Angular 库

java - 将多个对象或列表对象从 Spring Boot 发送到 Angular

Angular 2 Material - overlay 和 portal 是如何工作的?

javascript - 解决 "Document must be a JSON object"

Angular 2 如何实现多个布局组件

angular - 如何在 Angular 2+ 中模拟 @select

Angular5 TestBed useValue 似乎没有注入(inject)相同的对象实例