5

我正在使用angular2和i'im綁定數據從一個服務,問題是當我加載數據我應該過濾一個id,這是什麼我應該做的事:不能在內部使用* ngIF * ngFor:angular2

<md-radio-button 
     *ngFor="#item of items_list" 
     *ngIf="item.id=1" 
     value="{{item.value}}" class="{{item.class}}" checked="{{item.checked}}"> {{item.label}} 
</md-radio-button> 

,這是數據:

[ 
    { "id": 1, "value": "Fenêtre" ,"class":"md-primary" ,"label":"Fenêtre" ,"checked":"true"}, 
    { "id": 2, "value": "Porte Fenêtre" ,"class":"" ,"label":"Porte Fenêtre" } 

] 

由我只想用ID = 1被接受數據的方式,但我看到這個錯誤:

EXCEPTION: Template parse errors: 
Parser Error: Bindings cannot contain assignments at column 14 in [ngIf item.id=1] in [email protected]:16 (" 
     <md-radio-button 
       *ngFor="#item of items_list" 
       [ERROR ->]*ngIf="item.id=1" 
       value="{{item.value}}" class="{{item.class}}" checked="{{item.check"): [email protected]:16 

所以任何建議使用ngif和ngfor在一起?

+0

簡單,比答案更簡單:過濾器在組件中的數據,你把它傳遞給這個看法,根本沒有必要在視圖中去做。 –

回答

7

您可以使用下列內容:

*ngIf="item.id===1" 

代替

*ngIf="item.id=1" 

您嘗試分配的東西進入id財產(運營商=),而不是測試其值(運營商=====) 。

無論是ngFor和ngIf都不支持相同的元素。你可以嘗試這樣的事情:

<div *ngFor="#item of items_list"> 
    <md-radio-button 
     *ngIf="item.id===1" 
     value="{{item.value}}" class="{{item.class}}" 
     checked="{{item.checked}}"> 
    {{item.label}} 
    </md-radio-button> 
</div> 

<template ngFor #item [ngForOf]="items_list"> 
    <md-radio-button 
     *ngIf="item.id===1" 
     value="{{item.value}}" class="{{item.class}}" 
     checked="{{item.checked}}"> 
    {{item.label}} 
    </md-radio-button> 
</template> 
+0

謝謝,但問題仍然存在EXCEPTION:TypeError:無法讀取[item.id === 1在RadioFormesType1Component @ 11:16]中undefined的屬性'id' – firasKoubaa

+0

實際上,您需要創建一個子元素來應用'ngIf' 。同一元素上的'ngFor'和'ngIf'不支持... –

3

*ngIf*ngFor在同一標籤不被支持。您需要爲其中一個標籤使用明確的<template>標籤。

更新

代替<template>使用<ng-container>,其允許使用相同的語法內聯*ngIf*ngFor

+0

是的最好的解決方案是使用