【问题标题】:check with *ngIf, if there is an array or not (Angular 4)使用 *ngIf 检查是否存在数组(Angular 4)
【发布时间】:2018-07-25 22:22:21
【问题描述】:

我正在循环使用 *ngFor 的 json 文件。在遍历数据时,我想检查每个人,如果它没有颜色数组。我用 *ngIf 来做这件事。

JSON

[
  {
    "name": "Peter",
    "colors": [
      {
        "color": "blue"
      },
      {
        "color": "yellow"
      }
    ]
  },
  {
    "name": "Maria"
  }
  // has no colors array
]

HTML

<div *ngFor="let person of persons">
     <div *ngIf=" what comes here?? ">
        <p>{{person.name}} has no colors</p>
     </div>          
</div>

如果一个人没有颜色数组,我该如何检查?

【问题讨论】:

    标签: arrays json angular ngfor angular-ng-if


    【解决方案1】:

    试试这个

    <div *ngFor="let person of persons">
      <div *ngIf="person.colors && person.colors.length">
    

    用文字,它给了

    如果数组存在并且其中至少有一个元素

    相反的是

      <div *ngIf="!person.colors || !person.colors.length">
    

    您可以使用 Elvis operator

    缩短它
    <div *ngIf="!person.colors?.length">
    

    【讨论】:

    • 你可以,但我没有数组,所以很遗憾我不能使用它。不过还是谢谢
    • 因为on my side,它就像一个魅力@BlueCat
    • 我没有收到任何错误。但它不会显示“人没有颜色”。您的代码对我来说似乎是正确的,我会以同样的方式解决它,但我就是不知道可能出了什么问题。
    • 那你应该发布你的代码,因为我们不是通灵者!
    • 好吧,我没有比这更多的代码,我认为发布其余的代码有点不必要。但我赞成你的帖子,因为它应该是正确的,我认为可能只是我的配置有问题,而不是代码。
    【解决方案2】:

    很简单:

     <div *ngIf="!person.colors">
         <p>{{person.name}} has no colors</p>
     </div> 
    

    【讨论】:

    • 如果没有颜色,只有一个数组([]),这是行不通的。
    • 你是对的,我看到了你的(优秀的)答案,我赞成 BTW。但是 OP 的问题只是关于测试数组的存在与否。我回答了这个;你只是加倍努力:)
    • 我同意,这个问题要求数组的存在,但是拜托,我们都读了条件中的句子,你至少应该检查一下!并感谢您的支持!
    • 好吧,你没有我那么懒惰,所以你得到了投票而我没有:) 这不公平吗?
    • 我不是在谈论公平,而是关于......好吧,我不知道这个词。完整性?
    猜你喜欢
    • 2019-05-08
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 2017-12-10
    • 2021-05-27
    • 2011-06-20
    • 1970-01-01
    • 2020-09-10
    相关资源
    最近更新 更多