[英]How to start loop from index 1 instead of index 0 in *ngFor loop in angular?
我目前從虛擬 api 獲取一些數據,響應數據從 1 開始,索引當前從 0 開始。
如何從 1 而不是 0 開始索引循環?
以下是 *ngFor 的 html:
組件.html
<div class="all-users" >
<div class="nested-items" *ngFor="let data of flattenedResponse[0]; let i=index; " (click)="switchUsers(i)">
<h4>{{i}}</h4>
<img src="{{data.image}}" alt="profile">
</div>
</div>
為什么不只執行以下操作:
<div class="all-users" >
<div class="nested-items" *ngFor="let data of flattenedResponse[0]; let i=index; " (click)="switchUsers(i)">
<h4>{{i + 1}}</h4>
<img src="{{data.image}}" alt="profile">
</div>
</div>
我不知道有什么方法可以更改索引的起始位置,但這種方法適用於大多數情況
我如何從 1 而不是 0 開始索引循環
這里的正確答案是......你不能。
所以已經有一些建議,但我個人會避免破解你的標記來繞過 api 返回的數據結構。 讓您的標記需要知道太多關於您的服務器所做的事情通常不是一個好主意。
如果您的 api 返回的數組不是您標記的最佳格式 - 只需創建一個新的數據數組,並將您的標記指向該數組。 最好在處理 api 結果時在服務中執行此操作,但如果不出意外,請在 .ts 文件中執行此操作。
你試過嗎:
<div class="all-users">
<div class="nested-items" *ngFor="let data of flattenedResponse[0]; let i=index; " (click)="switchUsers(i+1)">
<h4>{{i+1}}</h4> <img src="{{data.image}}" alt="profile">
</div>
</div>
或者你可以像這樣跳過第一個元素:
<div class="nested-items" *ngFor="let data of flattenedResponse[0] | slice:1; let i=index; " (click)="switchUsers(i)"></div>
您可以使用*ngIf
顯式跳過第一個索引:
<div class="all-users" >
<div class="nested-items" *ngFor="let data of flattenedResponse[0]; let i=index;" (click)="switchUsers(i)">
<ng-container *ngIf="index !== 0">
<h4>{{i}}</h4>
<img src="{{data.image}}" alt="profile">
</div>
</ng-container>
</div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.