2017-04-20 31 views
1

如果在检查我的json中的库存数量时显示正确in-stock (store) or (online)消息的问题。如何正确检查ng中的条件是否使用操作员检查Angular2中的项目数量

所以情况是,如果库存不足10其视为low-stock如果如果大于10然后in-stock0然后out-of-stock

我的问题是当股价低于10*ngIf认为价值0以及因此它显示low-stock以及out-of-stock,或者如果股票10它显示low-stockin-stock。但如果股票大于10其罚款。

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

样品JSON -

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

模板与ngIf checks--

<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

回答

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

我preffer创建一个布尔值,并使用它:

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> 

为什么我preffer建立在我的组件的逻辑布尔,避免模板的逻辑推理是,因为也许在例如,将来的ngIf的逻辑比比较10更复杂。

1

添加&& checkStock.online != 0检查,如果股价低于10 and不等于0

相关问题