【问题标题】:How can I show with *ngIf only 1 time items of array that have the same value?如何仅使用 *ngIf 显示具有相同值的数组的 1 个时间项?
【发布时间】:2020-01-20 13:43:14
【问题描述】:

我有一个二维数组。示例:

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>

【问题讨论】:

  • 请显示weatherForecastjson数据
  • @AdritaSharma weatherForecast 是表格。
  • dhoe 是什么意思?
  • 我建议在组件代码中过滤掉所有不需要的数据,这样就不用在模板中过滤了。
  • @IvanKashtanov 问题是数据已经被过滤但我应该如何再次重新过滤它?请举例。

标签: angular typescript ionic-framework angular-ng-if


【解决方案1】:

如果我正确理解您想要实现的目标,这应该可行,

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>

【讨论】:

  • 嗨!谢谢回复。首先,您需要在 for 循环中添加 .length。而且它不起作用,它打印 aux is not a function。最后一行有问题。
  • 你是对的,我已经编辑了错误。对此感到抱歉。
  • 再次抱歉,但它不起作用。它充满了 0 个元素。但是,我再次有一个二维数组。所以没有区别,也没有用 *ngIf 解决我的专业问题。
  • if 条件有误,是“if 没有那一天”,我错过了 not !,导致结果为空..再次检查
  • 我认为,如果您想仅使用 *ngIf 来解决它,内部数组必须按天排序,那么我认为您的代码可以工作,尽管您还必须检查温度
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-25
  • 2016-12-19
  • 1970-01-01
相关资源
最近更新 更多