2017-04-20 29 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

相關問題