Template with *ngIf inner, not work after change model

你离开我真会死。 提交于 2019-12-12 11:25:28

问题


Problem

After the version of Angular 2.2. *, I noticed a problem in some components of my application, that after updating the data, the data was wrong in the view (it presented the list with the right size, but only with the data only of the first item) .

Demonstration

I created this Plunker with a simple example of the problem.

This type of use causes the problem:

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

Instructions for the problem to occur:

  1. Open the example in Plunker;
  2. Obverse the second block (Template with *ngIf:)
  3. Click the "Refresh" button;
  4. And look at the second block (Template with *ngIf:) again;

Question

What can be causing this problem and how to solve it?


回答1:


Inside template with *ngIf you have several TemplateRef. When data is changed it is mixed.

1) So you have to specify which template within ng-content you are exactly using for your purpose, for example:

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

and then in your ListComponent:

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

Plunker Example

P.S. but why aren't you using ngTemplateOutlet or ngForTemplate solutions?

For Example:

  • How to pass an expression to a component as an input in Angular2?

2) And i noticed in your example PrimeTemplate directive. So here is second option:

@ContentChild(PrimeTemplate) primeTmpl: PrimeTemplate;

and html:

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

Plunker Example



来源:https://stackoverflow.com/questions/41068032/template-with-ngif-inner-not-work-after-change-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!