![](/img/trans.png)
[英]How to use two different index variables inside the same ngFor in Angular 4
[英]Angular 5 ngfor let two variables at the same time
我需要為其分配兩個變量。 在Angular 5+中有類似的東西
<div *ngFor="let a of apple, let b of ball">
<a [routerLink]="['/ball',b]">
{{a}}
</a>
</div>
有什么建議嗎?
謝謝你的幫助。
更自然,而不是使用兩個數組,將數據組織為一個對象數組,如下所示:
this.things = [
{
apple: 'apple1',
ball: 'ball1'
},
{
apple: 'apple2',
ball: 'ball2'
}
]
然后你可以迭代這個數組,如下所示:
<div *ngFor="let thing of things">
<a [routerLink]="['/ball', thing.ball]">
{{ thing.apple }}
</a>
</div>
這也是更具可讀性和標准的做法。
看起來你的數組長度相同,即Parallel Arrays 。 你應該避免嵌套 ngFor
。
您可以使用一個數組的索引來查看另一個數組:
<div *ngFor="let a of apple; let i = index">
<a [routerLink]="['/ball', ball[i]]">{{a}}</a>
</div>
您可以使用ngFor的索引來訪問第二個數組的元素。
<ng-container *ngFor="let a of apple; index as i">
<h1>{{a}}</h1>
<h2>{{b[i]}}</h2>
</ng-container>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.