检查json
中的库存量时显示正确的in-stock (store) or (online)
消息时出现问题。
因此,情况是,如果股票小于其被视为low-stock
10
如果大于10
则in-stock
如果其0
则out-of-stock
。
我的问题是,当股票低于10
时,我的*ngIf
也看到了价值0
,因此它显示了low-stock
和out-of-stock
,或者如果股票10
,它会显示low-stock
和in-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 相比更复杂。