angular - 内部带有 *ngIf 的模板,更改模型后不起作用

标签 angular angular2-template

问题

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

示范

我创建了 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. 观察第二 block (带有*ngIf的模板:)
  3. 点击“刷新”按钮;
  4. 并再次查看第二个 block (Template with *ngIf:);

问题

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

最佳答案

使用 *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

关于angular - 内部带有 *ngIf 的模板,更改模型后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41068032/

相关文章:

angular - 模块 'DataTablesModule' 导入了意外值 'AppModule'。请添加@NgModule 注解

javascript - 向下滚动 3D 对象会重新加载移动版本的网页,但在 PC 网络浏览器中工作正常

angular - 运行 Angular i18n 时如何设置 messages.xlf 输出位置?

node.js - 如何等待发货完成后再从商店挑选。 Ngrx相关问题

Angular 2 错误 : Can't bind to 'innerhtml' since it isn't a known native property

html - 选择框默认选定值未显示在 Angular 2 的选择框中

html - angular2 自定义指令输入语法

angular - @Output 改变 bool 状态

javascript - 切换图像的宽度和高度

javascript - 模块 'NgAutoCompleteModule' 声明了意外的模块 'AppModule'。请添加@Pipe/@Directive/@Component注解