Udi Mazor
Udi Mazor

Reputation: 1826

How to get last child *ngFor list of components

I got a component that is called users-list. Inside this component there is *ngFor of directory-user component.

<directory-user-card *ngFor="let directoryUser of directoryUsers"
  [directoryUser]="directoryUser">

I need the last directory-user-card component to have different style. So I tries to use last-child at the parent component but with no success.

directory-user-card :last-child{
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
}

Any ideas?

Upvotes: 16

Views: 14401

Answers (1)

Nithya Rajan
Nithya Rajan

Reputation: 4884

You can use *ngFor - last variable to check whether the element is the last element or not.

if it's a last element of the loop then last variable will become true, so we can use [ngClass] to add/remove the class.

Angular Docs

Github Issue, where this is discussed as the correct way to handle this.

<directory-user-card *ngFor="let directoryUser of directoryUsers; let last = last"
  [directoryUser]="directoryUser" [ngClass]="{'last-child': last}">

.last-child{
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
}

Upvotes: 32

Related Questions