簡體   English   中英

如何在Angular 4的同一個ngFor中使用兩個不同的索引變量

[英]How to use two different index variables inside the same ngFor in Angular 4

我正在嘗試為每個僅打印到星期六的項目獲取一組不同的索引號。 一旦星期六開始打印,我的值應從0開始並繼續。 其他選項應具有相同的數值。 我該如何實現?

這是我在StackBlitz中的代碼

這正是為...創建模數的原因。

但要明確:在數組中不能有兩個索引。 這甚至都不合邏輯:如果您這樣做了,您是否不認為它們會具有相同的價值?

取而代之的是使用模(它是法文的名字,我不知道它是否翻譯過):

<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM