Levi J.
Levi J.

Reputation: 57

Accessing the first last item in an *ngFor?

I'm working on a personal application in Ionic in which I am trying to create a alphabetical header/divider for a list of games by checking the first letter of each game, and if the first letter is not the same as the last game's first letter(they are coming in sorted), generate a header.

Here's my firstLetter() function:

public firstLetter(name: any) {
    return name.charAt(0);
}

And here is my HTML/ng:

<ion-item-group *ngFor="let game of games; let i = index;">
        <ion-item-divider color="light" *ngIf="firstLetter(game.name) != firstLetter(game[i-1].name)">{{firstLetter(game.name)}}</ion-item-divider>
        <ion-item (click)="openGameSummary(game)">
          <h2>{{game.name}}</h2>
        </ion-item>
      </ion-item-group>

I am getting an error that the property 'name' cannot be found. Which, I assume is because I am using the wrong syntax.

What is the way to do this?

Upvotes: 3

Views: 2363

Answers (2)

robbannn
robbannn

Reputation: 5013

In your *ngIf you should change:
firstLetter(game[i-1].name)
to
firstLetter(games[i-1].name)

notice game to games.

What your'e doing now with firstLetter(game[i-1].name) is that you are trying to access the GameView-objects (game) property [i-1] which doesn't exist.

But if you change it to firstLetter(games[i-1].name) you will instead get the GameView-object from the games-array at index [i-1] and then be able to get that objects property name.

You also have to check for when i equals 0, because when it is games[i-1] will be games[-1] which is undefined, because there is no element at index -1. So as @Duannx wrote in his answer you should add i == 0 || to the start of your *ngIf, like so:

*ngIf="i == 0 || firstLetter(game.name) != firstLetter(games[i-1].name)"

If the first statement, in this case i == 0, is truthy when using || the second statement will never be evaluated and thus you will never try to access games[-1].

Upvotes: 1

Duannx
Duannx

Reputation: 8726

Change your *ngIf to:

*ngIf="i==0 || firstLetter(game.name) != firstLetter(games[i-1].name)"

Because when the first item is loaded, i==0, so games[i-1] is undefinded and it throws the error.

Upvotes: 3

Related Questions