1

I'm trying to render DOM elements based on a condition using directive ngIf. The condition is determined in a for loop using ngFor.

To explain further, in the template I have the following:

<div class="flex-card" *ngFor="let thing of things; trackBy: trackByFn">
<div class="card" *ngIf="displayCta">
...
</div>
</div>

In my component I have some corresponding property which is initialised to false:

 displayCta = false;

and the corresponding function used by trackBy in the same component is as:

trackByFn(index: any, item: any) {
  this.displayCta = (index % 3 === 0);
}

What I would expect is that the element with class card would be rendered when displayCta is set to true. Debugging this does show that displayCta toggles between true and false.

However what's rendered is purely based on the initial state of displayCta, not the logic that modifies it's state.

Is this down to the lifecycle of the component i.e. it looks at the initial state of displayCta, decides whether it's a truthy/falsey does all the rendering and after that the function trackByFn is invoked making no difference to what's rendered?

rilester
  • 35
  • 1
  • 4
  • 2
    Don't write track-by functions with side effects. There is no guarantee when it will be called. –  Jun 14 '17 at 16:24

2 Answers2

2

You can get the index in the *ngFor statement and assign it, then use that in the *ngIf.

<div class="flex-card" *ngFor="let thing of things; let i = index; trackBy: trackByFn">
<div class="card" *ngIf="i%3===0">

If this is just a quick example then you should update the actual model to track if it should be displayed or not. Putting the logic in the tracking function is not a good idea as already stated in the comments.

Igor
  • 60,821
  • 10
  • 100
  • 175
  • yes, that's a good approach. I've actually gone with this, and it seems to work
    – rilester Jun 14 '17 at 16:29
  • @rilester - glad to help. Please consider marking an answer once the 15 minute grace period has expired. – Igor Jun 14 '17 at 16:30
0

In this case displayCta will be changing quite a bit, and every single div will point to that same value. What you could do is add a field on thing in your trackByFn like so:

trackByFn(index: any, item: any) {
  item.show = (index % 3 === 0);
}

and then check for that in your ngIf

<div class="card" *ngIf="thing.show">

or do what Igor said.

LLL
  • 3,566
  • 2
  • 25
  • 44