![](/img/trans.png)
[英]Use ngFor for showing data in two different places from same Array Angular
[英]How to use two different index variables inside the same ngFor in Angular 4
這正是為...創建模數的原因。
但要明確:在數組中不能有兩個索引。 這甚至都不合邏輯:如果您這樣做了,您是否不認為它們會具有相同的價值?
取而代之的是使用模(它是法文的名字,我不知道它是否翻譯過):
<div *ngFor="let item of items; let i = index">
<span *ngIf="i % 7 === 5">It's Saturday !</span>
</div>
片段:
const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; const month = [...days, ...days, ...days, ...days]; month.forEach((day, i) => { if (i % 7 !== 5) { return; } console.log(day); });
編輯一個如果您有一個無序的天數組,“重新啟動索引”的最佳方法是將您的數組拆分為幾個。
如果要在周六重新啟動,請嘗試以下操作:
array=["monday","monday", "tuesday", "wednessday", "thursday", "friday", "saturday", "sunday", "saturday", "sunday"];
splitted = this.array.reduce((p, n) => {
if (n === 'saturday') { p.push([n]); return p; }
p[p.length - 1].push(n);
return p;
}, [[]]);
<p *ngIf="options != 'saturday' ">
{{i}}. First category : Value{{i}}
<p>
<p *ngIf="options == 'saturday'" style="color:red">
{{i}}. Saturday : Value{{i}}
</p>
</div>
</div>
編輯兩個,我希望這次是! 只需使用吸氣劑創建一個計數器,並在生命周期完成后將其初始化為零即可。
private counter;
get saturdayCounter() {
return this.counter++;
}
ngAfterContentChecked() {
this.counter = 0;
}
<p *ngIf="options == 'saturday'" style="color:red">
{{i}}. Saturday : Value{{saturdayCounter}}
</p>
根據您的“數組”創建一個新數組
let newArray:any[]=[];
let count:number=0;
this.array.forEach((a,index)=>{
if (a=="saturday")
{
newArray.push({type:1,index:count});
count++
}
else
newArray.push({type:0,index:index});
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.