具有*ngIf内部的模板,在更改模型后无法工作

Fer*_*eal 4 angular2-template angular

问题

在Angular 2.2的版本之后.*,我注意到我的应用程序的某些组件存在问题,即在更新数据后,视图中的数据是错误的(它显示的列表具有正确的大小,但仅包含第一项的数据).

示范

用一个简单的问题示例创建了这个Plunker.

这种使用会导致问题:

<list-component [data]="list">
  <template pTemplate let-item>
      <b *ngIf="item % 2 == 0">{{item}}</b>
      <del *ngIf="item % 2 != 0">{{item}}</del>
  </template>
</list-component>
Run Code Online (Sandbox Code Playgroud)

发生问题的说明:

  1. 在Plunker中打开示例;
  2. 正面第二个块(模板带*ngIf:)
  3. 单击"刷新"按钮;
  4. 然后再看第二个块(Template with *ngIf:);

什么可能导致这个问题,以及如何解决它?

yur*_*zui 5

在*ngIf的内部模板中,你有几个TemplateRef.当数据被改变时,它是混合的.

1)因此,您必须指定您正在使用的ng-content中的哪个模板,例如:

<list-component [data]="list">
  <template #tmpl let-item>  <== notice #tmpl
    <b *ngIf="item % 2 == 0">{{item}}</b>
    <del *ngIf="item % 2 != 0">{{item}}</del>
  </template>
</list-component>
Run Code Online (Sandbox Code Playgroud)

然后在ListComponent中:

@ContentChild('tmpl') template: TemplateRef<any>;
Run Code Online (Sandbox Code Playgroud)

Plunker示例

PS,但你为什么不使用ngTemplateOutletngForTemplate解决方案?

例如:

2)我注意到你的示例PrimeTemplate指令.所以这是第二种选择:

@ContentChild(PrimeTemplate) primeTmpl: PrimeTemplate;
Run Code Online (Sandbox Code Playgroud)

和HTML:

<template-loader [data]="item" [template]="primeTmpl.template"></template-loader>
Run Code Online (Sandbox Code Playgroud)

Plunker示例