Bryan
Bryan

Reputation: 3009

Angular 2: Using ngIf inside ngFor not working

I have the following ngFor loop:

<div *ngFor="let variety of varieties; let i=index">
    <div class="varietyTypeName">
        {{variety.VarietyTypeName}}            
    </div>
</div

Which prints out the following:

Greens
Greens
Greens
Fruits

I would like it to NOT print repeats, so instead (in this scenario), I would like it to print out:

Greens
Fruits

The VarietyTypeNames will always be grouped together in the array, so if there are multiple Greens, they will always come one after the other. Could I just use an ngIf inside of the loop and basically just tell it to only display the VarietyTypeName if it is NOT equal to the previous VarietyTypeName?

I tried implementing that logic below, but I'm getting an error. What am I doing wrong?

<div *ngFor="let variety of varieties; let i=index">
    <div *ngIf="variety[i].VarietyTypeName != variety[i - 1].VarietyTypeName" class="varietyTypeName">
        {{variety.VarietyTypeName}}
    </div>
</div

Here is the error message:

Cannot read property 'VarietyTypeName' of undefined

Upvotes: 2

Views: 3062

Answers (4)

koech
koech

Reputation: 596

In such a situation, you may want to use a pipe to filter the values before iterating over them. I am going to demonstrate a simple pipe that may help. N.B I am going to use the library lodash to simplify the example.

import { Pipe, PipeTransform } from '@angular/core'; import * as _ from 'lodash'; @Pipe({ name: 'filter' }) class FilterPipe { transform(input: any, term: any) { return _.uniqBy(input, term) } }

After importing the pipe as you always would in angular 2, this is how you would have your template code

<div *ngFor="let variety of varieties | filter : 'VarietyTypeName' "> {{variety.VarietyTypeName}} </div

P.S Remember to add lodash to your vendor files.

Upvotes: 0

Pardeep Jain
Pardeep Jain

Reputation: 86740

try this

<div *ngFor="let variety of varieties; let i=index">
    <div *ngIf="variety.VarietyTypeName != varieties[i - 1]?.VarietyTypeName" class="varietyTypeName">
        {{variety.VarietyTypeName}}
    </div>
</div

Upvotes: 3

Alexander Ciesielski
Alexander Ciesielski

Reputation: 10834

You should do that kind of logic inside your controller.

Filter all duplicates from the array and then just simply iterate over it.

let filteredVarieties = varieties.filter((variety, index) {
    return varieties.indexOf(variety) == index;
});

Now you can *ngFor over that newly created filteredVarieties

Upvotes: 2

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657308

I guess it should be

<div *ngFor="let variety of varieties; let i=index">
    <div *ngIf="variety.VarietyTypeName != i == 0 ? 0 : varieties[i - 1].VarietyTypeName" class="varietyTypeName">
        {{variety.VarietyTypeName}}
    </div>
</div

Upvotes: 1

Related Questions