【问题标题】:Template with *ngIf inner, not work after change model带有 *ngIf 内部的模板,更改模型后不起作用
【发布时间】:2016-12-09 20:05:11
【问题描述】:

问题

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

演示

我创建了this Plunker with a simple example 的问题。

这种使用方式会导致问题:

<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>

问题发生说明:

  1. 在 Plunker 中打开示例;
  2. 观察第二块(模板为*ngIf:)
  3. 点击“刷新”按钮;
  4. 再次查看第二个块(带有*ngIf 的模板:);

问题

什么可能导致此问题以及如何解决?

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    带有*ng的模板内部如果你有多个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>
    

    然后在您的 ListComponent 中:

    @ContentChild('tmpl') template: TemplateRef<any>;
    

    Plunker Example

    附:但是您为什么不使用ngTemplateOutletngForTemplate 解决方案?

    例如:

    2) 我在你的例子中注意到PrimeTemplate 指令。所以这是第二种选择:

    @ContentChild(PrimeTemplate) primeTmpl: PrimeTemplate;
    

    和html:

    <template-loader [data]="item" [template]="primeTmpl.template"></template-loader>
    

    Plunker Example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-06
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      相关资源
      最近更新 更多