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

时间:2017-04-20 15:27:08

标签: json angular

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

因此情况是,如果股票小于10,如果其大于low-stock,那么10如果in-stock那么0 out-of-stock {1}}。

我的问题是当该股票低于10我的*ngIf看到价值0时,它会显示low-stock以及out-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>

Plnkr sample

3 个答案:

答案 0 :(得分:2)

添加条件不匹配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>

答案 1 :(得分:1)

我很想创建一个布尔值并使用它:

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更复杂。

答案 2 :(得分:1)

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