【问题标题】:innerHtml is not painting ngFor template correctlyinnerHtml 未正确绘制 ngFor 模板
【发布时间】:2016-10-21 05:14:34
【问题描述】:

我正在使用角度 2.0.0-rc.2,

我的看法如下:

<div *ngFor="let kp of defltPge;let i=index" class="col-sm-4">
    <div class="iii" [innerHtml]="kp['content']"></div>
</div>

defltPge 逻辑的值如下

let tt4 = require('./dashStatic/tab-chat.html');
let tt5 = require('./dashStatic/tabs.html');
defltPge:[
    {
      "content":tt5
    },
    {
      "content":tt4
    }];

HTML如下:

tab-chat.html

<div class="item-remove-animate item-avatar item-icon-right item item-complex item-right-editable" *ngFor="let chat of chats">
      <a class="item-content">
        <img src="img/ben.png" src="img/ben.png">
        <h2 class="ng-binding">{{chat.name}}</h2>
        <p class="ng-binding">{{chat.lastText}}</p>
        <i class="fa fa-chevron-right"></i>
      </a>
    </div>

tabs.html

<h1>
    Dashboard
  </h1>

但是 tab-chat.html 没有正确呈现它只是显示未编译的代码如下:

{{chat.name}}
{{chat.lastText}}

【问题讨论】:

    标签: angular angular2-template angular2-directives


    【解决方案1】:

    Angular2 不处理 HTML 中动态添加的 [innerHtml]=...element.appendChidl() 或类似的绑定。

    Angular2 只处理静态添加到组件模板的 HTML。

    您可以使用ViewContainerRef.createComponent() 动态添加组件。 Angular 2 dynamic tabs with user-click chosen components 显示了一个示例。

    【讨论】:

    • 你能给我一个例子如何在我的情况下使用它吗?
    • 如果tabs-chat.html是你要动态添加的HTML,你需要在模板中创建一个包含这个HTML的新组件。使用ViewContainerRef.createComponent(),您可以动态添加此组件,或者您可以使用我的dcl-wrapper 组件,如链接答案所示。
    • 但问题是 defltPge 长度是动态的,所以在你的方法中我怎样才能动态地创建没有组件?
    • 这正是链接答案所展示的。 &lt;dcl-wrapper *ngFor="let kp of defltPge" [type]="defltPge.type"&gt; 其中defltPge 需要包含您要实例化的组件的类型(对类的引用,一个字符串是不够的)。如果您想在 HTML 中使用像 {{}} 这样的绑定,那么您需要一种将数据传递给动态实例化组件的方法。动态添加的组件不支持[data]="..." 类型的绑定来传递数据。链接的答案在代码中包含如何传递数据的注释。
    猜你喜欢
    • 2013-02-25
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    相关资源
    最近更新 更多