首页 > 解决方案 > 如果为真或其他方式(Angular),如何在 ngFor 中跳过

问题描述

我有一个更理论的问题,在我的应用程序中,我有一个组件,它作为@Input一个包含对象的数组接收,其中可以是(或不是)三个类别之一,也分为三种类型,所以这里是主要类别:

  1. 汽车定义
  2. car_fyr
  3. 汽车间谍

而且它们每个都可以带有零件_mid_low显示其优先级

所以 arr 看起来像这样:

[
  {id: 2, key: "car_def"},
  {id: 2, key: "car_def_low"},
  {id: 2, key: "car_fyr"},
  {id: 2, key: "car_fyr_mid"}
]
 OR
[
  {id: 2, key: "car_spy"},
  {id: 2, key: "car_def"},
  {id: 2, key: "car_fyr"},
  {id: 2, key: "car_fyr_mid"}
]...

如果我收到某个类别 - 我需要在模板中显示它,但只有 ONCE 和主名称。而且它附近应该是一个图标,我有另一个函数,需要传递一个类别作为参数。所以从例子来看,它应该是car_def, car_fyr, 或car_spy, car_def, car_fyr

至于现在,我在 .ts 中写了一个函数

@Input cars;
ngOnInit(): void {
    this.isDisplayed(this.cars);
}
isDisplayed(arr) {
    let str = arr.map(car => car.key).join(' ');
    if (str.match('car_def')) {
      this.isDef = true;
    }
    if (str.match('car_fyr')) {
      this.isFyr = true;
    }
    if (str.match('car_spy')) {
      this.isSpy = true;
    }
  }

在 HTML 中我使用 *ngIf

<div #container>
  <div *ngIf="isDef">
    CAR_DEF <icon icon="{{displayIcon('car_def')}}"></icon>
  </div>
  <div *ngIf="isFyr">
    CAR_FYR <icon icon="{{displayIcon('car_fyr')}}"></icon>
  </div>
  <div *ngIf="isSpy">
    CAR_SPY <icon icon="{{displayIcon('car_spy')}}"></icon>
  </div>
</div>

所以,我的问题是,有没有更好的方法来写它?我想过*ngFor但不知道在这种情况下如何只显示一次类别......

非常感谢您的任何建议!

标签: javascripthtmlangulartypescript

解决方案


这会简化一点——当您添加更多类型类别时,您的 HTML 不需要更新......

@Input cars;
typeData: any
 
isDisplayed(arr) {
    let str = arr.map(car => car.key).join(' ');
    if (str.match('car_def')) {
      this.typeData = {typeName: "CAR_DEF", icon: this.displayIcon('car_def')};
    } else if (str.match('car_fyr')) {
      this.typeData = {typeName: "CAR_FYR", icon: this.displayIcon('car_fyr')};
    } else if (str.match('car_spy')) {
      this.typeData = {typeName: "CAR_SPY", icon: this.displayIcon('car_spy')};
    }
  }


<div #container>
  <div *ngIf="typeData.typeName">
    {{typeData.typeName}} <icon icon="{{typeData.icon}}"></icon>
  </div>
</div>

推荐阅读