【问题标题】:HTML String does not display correctly [duplicate]HTML 字符串无法正确显示 [重复]
【发布时间】:2017-05-08 09:49:06
【问题描述】:

已经有一段时间了,我知道有一个解决方案。我正在从 Firebase 3 中检索一个对象。该字段是一个包含 html 的字符串。我将值插入到 Angular2 component.html 中。 Angular2中没有<b>标签,有没有办法、函数调用、方法来渲染html?

   key: Description
   value: <p>Hello World</p>

在我的 Angular 组件 HTML 中

   <h3>Description</h3><div>{{something.Description}}</div>

html 呈现为:

【问题讨论】:

标签: javascript html angular


【解决方案1】:

ng-bind-html(正如许多人所建议的那样)不是 Angular2 解决方案。请改用[innerHTML]

<div [innerHTML]="something.Description"></div>

【讨论】:

    【解决方案2】:

    实现这一目标的几种方法:

    1) 尝试改用 .append angular 方法。

    &lt;h3&gt;Description&lt;/h3&gt;&lt;div id='divID'&gt;&lt;/div&gt;

    var myElement = angular.element( document.querySelector( '#divID' ) );
    myElement.append('<p>Your values/variables</p>');
    

    2) 对于 Angular 2:

    <div [innerHTML]="theHtmlString">
    </div>
    

    3) 对于那些仍然使用 Angular 1 vs 2 的人:

    另一种方式,是ng-bind-html,类似这样:

    HTML

    <div ng-controller="ExampleController">
     <p ng-bind-html="myHTML"></p>
    </div>
    

    JS

    angular.module('bindHtmlExample', ['ngSanitize'])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.myHTML =
         '<h3>Description:</h3>' +
         '<div> YOUR VARIABLES </div>';
    }]);
    

    【讨论】:

    • 我建议删除您答案的ng-bind-html 部分,只是因为它可能会使将来偶然发现这个问题的读者感到困惑-这是不正确的,因为 OP 明确表示他正在寻找Angular 2 解决方案。 编辑:不错的编辑:)
    猜你喜欢
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 2021-02-23
    相关资源
    最近更新 更多