[angular] 속성의 값으로 인덱스를 갖는 ngFor

ngFor현재 루프를 유지 하는 간단한 루프가 있습니다 index. 해당 index값을 속성 에 저장하여 인쇄 할 수 있습니다. 그러나 이것이 어떻게 작동하는지 알 수 없습니다.

나는 기본적으로 이것을 가지고있다 :

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

#i속성에 값을 저장하고 싶습니다 data-index. 몇 가지 방법을 시도했지만 그중 아무것도 작동하지 않았습니다.

여기에 데모가 있습니다 : http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview

속성에 index값을 저장하려면 어떻게 data-index해야합니까?



답변

이 구문을 사용하여 색인 값을 HTML 요소의 속성으로 설정합니다.

각도> = 2

let대신 값을 선언하는 데 사용해야 합니다 #.

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

각도 = 1

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

여기에 업데이트 된 plunkr은 다음과 같습니다 http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview .


답변

Angular 5/6/7/8에서 :

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

이전 버전에서

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

Angular.io ▸ API ▸ NgForOf

단위 테스트 예

또 다른 흥미로운 예


답변

이것에 대한 업데이트, Thierry의 대답은 여전히 ​​정확하지만 Angular2는 다음과 관련하여 업데이트되었습니다.

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

#i = index지금해야let i = index

편집 / 업데이트 :

*ngFor그것이 있어야이 그래서 예를 들면, 당신은 foreach 문에 원하는하고있는 요소에 있어야합니다 :

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

편집 / 업데이트

각도 5

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

EDIIT / 업데이트

앵귤러 7/8

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


답변

나는 이미 전에 대답했다고 생각하지만 정렬되지 않은 목록을 채우는 경우 수정하면 *ngFor반복하려는 요소가 나타납니다. 그래서 그것은 insdide해야합니다 <li>. 또한 Angular2는 이제 let을 사용하여 변수를 선언합니다.

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


답변

다른 답변은 정확하지만 [attr.data-index]완전히 생략하고 사용할 수 있습니다

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


답변

당신은 사용할 수 있습니다 [attr.data 색인을] 각도 버전 2 이상에서 사용할 수있는 데이터-index 속성에 인덱스를 저장하는 직접.

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


답변

이 시도

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