ChatGPT解决这个技术问题 Extra ChatGPT

ngFor with index as value in attribute

I have a simple ngFor loop which also keeps track of the current index. I want to store that index value in an attribute so I can print it. But I can't figure out how this works.

I basically have this:

<ul *ngFor="#item of items; #i = index" data-index="#i">
    <li>{{item}}</li>
</ul>

I want to store the value of #i in the attribute data-index. I tried several methods but none of them worked.

I have a demo here: http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview

How can I store the index value in the data-index attribute?


t
tobias47n9e

I would use this syntax to set the index value into an attribute of the HTML element:

Angular >= 2

You have to use let to declare the value rather than #.

<ul>
    <li *ngFor="let item of items; let i = index" [attr.data-index]="i">
        {{item}}
    </li>
</ul>

Angular = 1

<ul>
    <li *ngFor="#item of items; #i = index" [attr.data-index]="i">
        {{item}}
    </li>
</ul>

Here is the updated plunkr: http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview.


In fact, the attr. is a syntax to tell Angular2 to set the value of the expression to the attribute name. It's not just like evaluating JSON, I guess ;-) See this link: angular.io/docs/ts/latest/guide/template-syntax.html
Thanks, that does the trick. Also, I meant to put the ngFor on the li instead of the ul.
I rolled back the recent edit in order to have both the original answer and the new updated code value. I was searching for some early beta stuff and saw that this answer was modified, so it no longer applied to the beta version of angular 2.
UPDATE: 08/2017
as of Oct 17, 2018 Angular 6 is using *ngFor="let item of items; index as i" See Leo's answer below.
L
Leo

In Angular 5/6/7/8:

<ul>
  <li *ngFor="let item of items; index as i">
    {{i+1}} {{item}}
  </li>
</ul>

In older versions

<ul *ngFor="let item of items; index as i">
  <li>{{i+1}} {{item}}</li>
</ul>

Angular.io ▸ API ▸ NgForOf

Description

Local variables

Unit test examples

ng_for_spec.ts

Another interesting example

Grouping


this is it! Working as of Oct 17, 2018 . Thank you. (why they keep changing syntax, so annoying?
this is a better and simple answer than the first one.
index as i works great, thank you. But isn't the *ngFor meant to go on the element to be repeated (e.g. the <li> in this case)? The code you suggested creates multiple <ul>s rathers than multiple <li>s.
index as i is more elegant than let i = index
W
Wesley Coetzee

Just an update to this, Thierry's answer is still correct, but there has been an update to Angular2 with regards to:

<ul *ngFor="let item of items; let i = index" [attr.data-index]="i">
  <li>{{item}}</li>
</ul>

The #i = index should now be let i = index

EDIT/UPDATE:

The *ngFor should be on the element you're wanting to foreach, so for this example it should be:

<ul>
  <li *ngFor="let item of items; let i = index" [attr.data-index]="i">{{item}}</li>
</ul>

EDIT/UPDATE

Angular 5

<ul>
  <li *ngFor="let item of items; index as i" [attr.data-index]="i">{{item}}</li>
</ul>

EDIIT/UPDATE

Angular 7/8

<ul *ngFor="let item of items; index as i">
  <li [attr.data-index]="i">{{item}}</li>
</ul>

And #item should be let item ;-)
m
monica

I think its already been answered before, but just a correction if you are populating an unordered list, the *ngFor will come in the element which you want to repeat. So it should be insdide <li>. Also, Angular2 now uses let to declare a variable.

<ul>
    <li *ngFor="let item of items; let i = index" [attr.data-index]="i">     
               {{item}}
    </li>
</ul>

I think that it is best practice to specify the *ngFor directive in ul tag
  • {{item}}
If you specify ngFor in the ul tag, then the entity that will be repeated will be ul, but here u dont want to repeat the ul, you just want to iterate on the list elements i.e. li.
C
Chris Farmer

The other answers are correct but you can omit the [attr.data-index] altogether and just use

<ul>
    <li *ngFor="let item of items; let i = index">{{i + 1}}</li>
</ul

A
Ande Yashwanth

Adding this late answer to show a case most people will come across. If you only need to see what is the last item in the list, use the last key word:

<div *ngFor="let item of devcaseFeedback.reviewItems; let last = last">
  <divider *ngIf="!last"></divider>
</div>

This will add the divider component to every item except the last.

Because of the comment below, I will add the rest of the ngFor exported values that can be aliased to local variables (As are shown in the docs):

$implicit: T: The value of the individual items in the iterable (ngForOf).

ngForOf: NgIterable: The value of the iterable expression. Useful when the expression is more complex then a property access, for example when using the async pipe (userStreams | async).

index: number: The index of the current item in the iterable.

count: number: The length of 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.


How do you know this? Is there some kind of documentation somewhere, or a typescript file, or something that lists all the keywords we can use?
@EliezerBerlin In the official angular ngFor docs it is mentioned angular.io/api/common/NgForOf I became a better Angular dev once i started going to docs before SO or Google I promise if you do that you will become a better Angular dev, the docs have come a long way and Angular is really mature now.
Damn. I was hoping to find a similar list for Angular Material's tables by browsing through the .ts files, or something. The documentation for Material Tables is a lot, lot worse.
It is in common.d.ts in angular/common thats where ngFor comes from
A
Arun s

You can use [attr.data-index] directly to save the index to data-index attribute which is available in Angular versions 2 and above.

    <ul*ngFor="let item of items; let i = index" [attr.data-index]="i">
         <li>{{item}}</li>
    </ul>

v
vijay kanaujia

with laravel pagination

file.component.ts file

    datasource: any = {
        data: []
    }

    loadData() {
        this.service.find(this.params).subscribe((res: any) => {
            this.datasource = res;
        });
    }

html file

   <tr *ngFor="let item of datasource.data; let i = index">
       <th>{{ datasource.from + i }}</th>
   </tr>

C
Chirag

Try this

<div *ngFor="let piece of allPieces; let i=index">
{{i}} // this will give index
</div>

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now