Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
907 views
in Technique[技术] by (71.8m points)

typescript - Angular io (4) *ngFor first and last

I am trying to tell whether an item in an *ngFor is the first or last element to style a container. Is there a way to do something like this?

<md-expansion-panel *ngFor="let item of items" *ngClass="{ 'first' : item.isFirst }">
  <content></content>
</md-expansion-panel>

Thanks for any help offered!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Inside the ngFor you have access to several variables:

  • index: number: The index of the current item in the iterable.
  • first: boolean: True when the item is the first item in the iterable.
  • last: boolean: True when the item is the last item in the iterable.
  • even: boolean: True when the item has an even index in the iterable.
  • odd: boolean: True when the item has an odd index in the iterable.

So:

<md-expansion-panel *ngFor="let item of items; first as isFirst"
    *ngClass="{ 'first' : isFirst }">
  <content></content>
</md-expansion-panel>

Documentation at https://angular.io/api/common/NgForOf gives this example:

<li *ngFor="let user of userObservable | async as users; index as i; first as isFirst">
   {{i}}/{{users.length}}. {{user}} <span *ngIf="isFirst">default</span>
</li>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...