javascript - 如果为真或其他方式(Angular),如何在 ngFor 中跳过
问题描述
我有一个更理论的问题,在我的应用程序中,我有一个组件,它作为@Input
一个包含对象的数组接收,其中可以是(或不是)三个类别之一,也分为三种类型,所以这里是主要类别:
- 汽车定义
- car_fyr
- 汽车间谍
而且它们每个都可以带有零件_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
但不知道在这种情况下如何只显示一次类别......
非常感谢您的任何建议!
解决方案
这会简化一点——当您添加更多类型类别时,您的 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>
推荐阅读
- javascript - 如何解决 POST http://127.0.0.1:8000/bkash/payment/create 403(禁止)?(Django + ajax)
- c# - 用户更改密钥时保存模型时出错
- php - 如何连接多个mysql db
- sql - 有或没有 where 条件的查询结果相同
- javascript - 如何在保持纵横比而不切断画布的同时使 HTML 画布适合屏幕?
- python - Python Pandas:从单元格中提取数据并将其转换为列
- typescript - Typescript - 在指定特定字段值的同时定义基于其他类型的类型
- windows - 如何抑制或解决窗口找不到...确保正确输入名称
- css - 角度材料和materila-ui和Materializecss是否与材料设计有关?
- spring-boot - 组 main 中的调度程序工作人员中的 Azure BlobClient.beginCopy(..) 错误失败并出现未捕获的异常