【问题标题】:How to write a condition with *ngFor to check two values如何使用 *ngFor 编写条件来检查两个值
【发布时间】:2023-03-06 17:42:02
【问题描述】:

我正在使用角度 7

如上所示,我的组件中有一个 Stock Array。

private stocks:any = [];

 [{
        "scripcode": "M&M",
        "open": "671.95",
        "high": "676.90",
        "low": "661.60",
        "exchange": "NSE"
    }, {
        "scripcode": "DRREDDY",
        "open": "2616.00",
        "high": "2684.00",
        "low": "2603.00",
        "exchange": "NSE"
    }, {
        "scripcode": "GRASIM",
        "open": "722.00",
        "high": "743.60",
        "low": "722.00",
        "exchange": "NSE"
    }
    ]

在我的模板类中,我以以下方式显示它

<tbody>
    <tr mdbTableCol *ngFor="let el of stocks">
      <th scope="row">{{el.scripcode}}</th>
      <td>{{el.open}}</td>
      <td>{{el.low}}</td>
      <td>{{el.high}}</td>
    </tr>
  </tbody>

是否可以写条件,如果open和low的值相同,那么我只需要显示该行,否则不需要

感谢您的阅读

【问题讨论】:

  • "那么只有我需要显示",显示低单元格和高单元格?如果是这样,&lt;ng-contianer *ngIf="el.high===el.low"&gt; &lt;td&gt;{{el.high}}&lt;/td&gt; &lt;td&gt;{{el.low}}&lt;/td&gt;&lt;/ng-container&gt;?
  • 如果它们相同,你需要显示什么?这是检查值是否相同的方法*ngIf="el.high === el.low"
  • 如果开盘价和最低价相同,则显示表格行。否则跳过该股票

标签: angular


【解决方案1】:

我会利用 *ngIf 来处理这样的事情。由于您需要使用两个模板绑定,您可以使用 ng-container 将其包装起来

<tbody>
  <ng-container *ngFor="let el of stocks">
    <tr mdbTableCol *ngIf="el.low === el.open">
      <th scope="row">{{el.scripcode}}</th>
      <td>{{el.open}}</td>
      <td>{{el.low}}</td>
      <td>{{el.high}}</td> 
    </tr>
  </ng-container>
</tbody>

这个tr只有在两者不相同时才会显示。

【讨论】:

  • 技术正确但条件不正确。
  • 感谢您的提醒
  • 虽然这是正确的,但这不应该用于大型集合,性能方面。尝试先过滤集合,然后使用ngFor,并结合OnPush。
  • @dince12 - 欢迎您,但条件仍然不正确。 :-)
  • 严格检查这两个值,我认为 *ngIf 在条件为真时显示,在假时隐藏?
猜你喜欢
  • 1970-01-01
  • 2018-05-11
  • 2021-09-01
  • 2012-01-06
  • 2018-12-14
  • 2014-11-24
  • 2018-07-31
  • 2020-06-19
  • 1970-01-01
相关资源
最近更新 更多