Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last child *ngFor list of components

Tags:

css

angular

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?

like image 353
Udi Mazor Avatar asked Jul 05 '19 12:07

Udi Mazor


1 Answers

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;
}
like image 172
Bear Nithi Avatar answered Nov 19 '22 13:11

Bear Nithi