Search code examples
jsontypescriptangularangular2-directivesangular2-services

Can't use *ngIF inside *ngFor : angular2


i'm using angular2 and i'im binding data from a service , the probleme is when i'm loading data i should filter it by an id , , this is what i'm supposed to do :

<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>

and this is the data:

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

]

by the way i want just the data with id =1 to be accepted , but i'm seeing this error:

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

so any suggestion to use ngif and ngfor together ?


Solution

  • You could use the following:

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

    instead of

    *ngIf="item.id=1"
    

    You try to assign something into the id property (operator =) instead of testing its value (operator == or ===).

    Moreoever both ngFor and ngIf on the same element aren't supported. You could try something like that:

    <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>
    

    or

    <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>