2017-04-05 44 views
2

現在我正在使用ngIf來查看Item Id是否爲1並且它做了一些樣式更改,但第二個語句仍然針對沒有item Id爲1的所有其他對象運行。我明白爲什麼會發生這種情況,但是如果在數組中的任何對象中都不存在Item Id 1,那麼是否只有運行第二條語句的方法?多謝ng如果檢查是否存在變量

<div *ngFor="let item of items">  
    <div *ngIf="(item.details.id == 1)"> 
     Do Somthing 
    </div> 

    <div *ngIf="(item.details.id != 1)"> 
     Do Somthing 
    </div> 
    </div> 
+0

也更新您的JSON – Aravind

回答

0

您應該嚴格運營商如下

<div *ngFor="let item of items">  
    <div *ngIf="(item.details.id === 1)"> 
     Do Somthing 
    </div> 

    <div *ngIf="!(item.details.id === 1)"> 
     Do Somthing 
    </div> 
    </div> 
+1

OP的含義是什麼如果'items'中的某個元素不包含'details.id = 1',則不執行第二個元素。 – echonax

2

可以比較在組件代碼:

// private oneExists: boolean = false; 
this.oneExists = this.items.filter(item => item.details.id === 1).length > 0; 

模板:

<div *ngFor="let item of items">  
    <div *ngIf="item.details.id === 1"> 
    Do Something 
    </div> 

    <div *ngIf="! oneExists"> 
    Do Something 
    </div> 
</div> 
+0

因此,Items是在另一個數組中,所以它更像是'let item of product.items'我在使用過濾器訪問構造函數中的某些項時遇到了一些問題,有什麼建議什麼是爲此目的訪問項目的最佳方式知道產品是否也是產品陣列的孩子。 – DN0300

+0

你可能不應該在構造函數中訪問它們。 「this.product.items」初始化在哪裏?我想在'ngOnInit'中調用一個promise。如果是這樣,請將我的過濾代碼移到那裏如果在其他地方,請在'this.product.items'初始化後移動該代碼_right。並聲明'private oneExists:boolean = false;'在開始的某處。 – gsc

相關問題