4

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?

Fernando Leal
  • 9,875
  • 4
  • 24
  • 46

1 Answers1

5

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:

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

Community
  • 1
  • 1
yurzui
  • 205,937
  • 32
  • 433
  • 399