仅当满足条件时才使用 *ngFor 迭代 json 的元素

iterate elements of a json using *ngFor only if they met a condition

我正在开发一个通过服务调用 json 的 angular 4 项目,一切都很好,除了一件事情,我的 json 具有以下简化结构了解问题:

{
  "animals" [

   {
    "name" : "dog"
    "subgroup": "vertebrate"
    "class" : "mammal"
   },
   {
    "name" : "pig"
    "subgroup": "vertebrate"
    "class" : "mammal"
   },
   {
    "name" : "cat"
    "subgroup": "vertebrate"
    "class" : "mammal"
   },
   {
    "name" : "snake"
    "subgroup": "vertebrate"
    "class" : "reptile"
   },
   {
    "name" : "lizzard"
    "subgroup": "vertebrate"
    "class" : "reptile"
   },
   {
    "name" : "crocodile"
    "subgroup": "vertebrate"
    "class" : "reptile"
   },
 ]
}

我只想用 "class" 迭代对象:"reptile"

我做了这个结构:

  <div class="col-12 mb-3" *ngFor="let reptiles of animals">
    <div *ngIf = "reptiles.class == reptile">
      <div class="row">
        <div class="col-12">
          <h5 class="py-3 bg-dark text-white pl-3 mx-0 mb-3">{{reptiles.name}}</h5>
          <p class="py-3 bg-dark text-white font-weight-light pl-3 m-0">{{reptiles.class}}</p>
        </div>
      </div>
    </div>
  </div>

但是发生的事情是它迭代了三个空

<div class="col-12 mb-3" *ngFor="let reptiles of animals">
</div>

对应哺乳动物,我希望对象完全不迭代,我只想迭代class "reptile"的对象。 我怎样才能做到这一点?

简单的解决方法是使用 ng-container 而不是 div 来迭代:

<ng-container *ngFor="let reptiles of animals">
    <div class="col-12 mb-3" *ngIf="reptiles.class == reptile">
        <div>
            <!-- ... -->
        </div>
    </div>
</ng-container>

当然,模板现在仍然迭代这些条目,但它不会为它创建任何 DOM 节点(ng-container 的魔力).

可能更好的解决方法是在您的组件中过滤并仅将您要显示的数据传递给模板:

// In your controller after receiving the animals data:
this.reptiles = this.animals.filter(a => a.class === "reptile");

// Template
<div *ngFor="let reptile of reptiles">...</div>

您还可以编写一个 filterBy 管道或从现有库(例如 ngx-pipes)中获取一个。但请注意 Angular 不鼓励这样做,因为它很容易成为性能陷阱。

您只需要像这样在组件中过滤数据:

this.filteredAnimals = this.animals.filter(animal => animal.class === "reptile"); // now use filteredAnimals in html template

希望对您有所帮助

我觉得你可以用这个

只需按 class 属性:

筛选
filterItemsOfType(type){
    return this.items.filter(x => x.class == type);
}

干杯,

@carlosrojas_o