簡體   English   中英

如何使用 *ngIf 僅顯示具有相同值的數組的 1 個時間項?

[英]How can I show with *ngIf only 1 time items of array that have the same value?

在此處輸入圖片說明 我有一個二維數組。 例子 :

weatherForecast = [
  [Weather(Monday, 10C, 11:00), (Weather(Monday, 12:00)],
  [Weather(Tuesday, 10C, 11:00),(Weather(Tuesday, 12:00)]
];

如果值相同,我如何每天打印一次。 代碼:

<ion-item>
  <ion-grid>
    <ion-row *ngFor="let forecast of weatherForecast; let i = index">
      <ion-col *ngFor="let weatherData of forecast; let j = index">
        <div *ngIf="weatherData[j].day !== forecast[j - 1].day">
          {{ forecast[j].day }}
        </div>
      </ion-col>
      <ion-col *ngFor="let weatherData of forecast; let j = index">
        <div>
          {{ forecast[j].temperature }}
        </div>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-item>

如果我正確理解您想要實現的目標,這應該可行,

let aux;
let filterForecast = [];
for (let i = 0; i < weatherForecast.length; i++) {
  aux = {};
  for (let j = 0; j < weatherForecast[i].length; j++) {
    if (!aux.hasOwnProperty(weatherForecast[i][j].day)) {
      aux[weatherForecast[i][j].day] = weatherForecast[i][j];
    }
  }
  filterForecast.push(Object.values(aux));
}

我使用了一個非常簡單的代碼,您必須根據自己的代碼進行調整。 這種方法解決了代碼而不是模板中的問題。 我只是使用字典來保留不同的日子,然后將字典的值添加到結果中。 有了這個,您將不得不在模板中使用filterForecast而不是weatherForecast

假設內部數組按天排序,那么只需使用*ngIf

<ion-item>
  <ion-grid>
    <ion-row *ngFor="let forecast of weatherForecast; let i = index">
      <ion-col *ngFor="let weatherData of forecast; let j = index">
        <div *ngIf="j === 0 || weatherData.day !== forecast[j - 1].day">
          {{ weatherData.day }}
        </div>
      </ion-col>
      <ion-col *ngFor="let weatherData of forecast; let j = index">
        <!-- I am not sure if you need to check here too -->
        <div>
          {{ weatherData.temperature }}
        </div>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-item>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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