如何正确检查 ng 中的条件如果使用运算符在 Angular2 中检查项目数量



检查json中的库存量时显示正确的in-stock (store) or (online)消息时出现问题。

因此,情况是,如果股票小于其被视为low-stock10如果大于10in-stock如果其0out-of-stock

我的问题是,当股票低于10时,我的*ngIf也看到了价值0,因此它显示了low-stockout-of-stock,或者如果股票10,它会显示low-stockin-stock。但如果股票大于10罚款。

如何正确检查股票以显示正确的股票信息?

示例 json --

this.checkStock = {
"online": 0,
"store": 10
}

带有ngIf检查的模板--

<p>
<span *ngIf="checkStock.online >= 10 "><i class="fa fa-check-circle fa-2x text-success" aria-hidden="true"></i> In-stock (Online)</span>
<span *ngIf="checkStock.online <= 10 "><i class="fa fa-exclamation-circle fa-2x text-warning" aria-hidden="true"></i> Low stock (Online)</span>
<span *ngIf="checkStock.online == 0"><i class="fa fa-times-circle fa-2x text-danger" aria-hidden="true"></i> Out-of-stock (Online)</span>
</p>
<p>
<span *ngIf="checkStock.store >= 10 "><i class="fa fa-check-circle fa-2x text-success" aria-hidden="true"></i> In-stock (store)</span>
<span *ngIf="checkStock.store <= 10 "><i class="fa fa-exclamation-circle fa-2x text-warning" aria-hidden="true"></i> Low stock (store)</span>
<span *ngIf="checkStock.store == 0"><i class="fa fa-times-circle fa-2x text-danger" aria-hidden="true"></i> Out-of-stock (store)</span>
</p>

普罗提样本

只需添加不匹配 0 的条件:

<span *ngIf="checkStock.online >= 10 "><i class="fa fa-check-circle fa-2x text-success" aria-hidden="true"></i> In-stock (Online)</span>
<span *ngIf="checkStock.online <= 10 && checkStock.online > 0"><i class="fa fa-exclamation-circle fa-2x text-warning" aria-hidden="true"></i> Low stock (Online)</span>
<span *ngIf="checkStock.online == 0"><i class="fa fa-times-circle fa-2x text-danger" aria-hidden="true"></i> Out-of-stock (Online)</span>

添加&& checkStock.online != 0以检查库存是否小于 10and不等于 0

我更喜欢创建布尔值并使用它们:

export class App {
name:string;
checkStock: any;
outOfStock: boolean = false;
lowStock: boolean = false;
inStock: boolean = false;
constructor() {
this.name = `Angular! v${VERSION.full}`
this.checkStock = {
"online": 0,
"store": 10
}
this.outOfStock = this.checkStock.online == 0;
this.lowStock = this.checkStock.online <= 10;
this.inStock = this.checkStock.online >= 10;
}
}

在模板中:

<p>
<span *ngIf="inStock"><i class="fa fa-check-circle fa-2x text-success" aria-hidden="true"></i> In-stock (Online)</span>
<span *ngIf="lowStock"><i class="fa fa-exclamation-circle fa-2x text-warning" aria-hidden="true"></i> Low stock (Online)</span>
<span *ngIf="outOfStock"><i class="fa fa-times-circle fa-2x text-danger" aria-hidden="true"></i> Out-of-stock (Online)</span>
</p>

我更喜欢在组件的逻辑中创建布尔值而避免在模板中创建逻辑的原因是,例如,将来ngIf的逻辑可能比与 10 相比更复杂。

最新更新