Cannot use * ngIF inside * ngFor: angular2

I use angular2 and i'im bind data from the service, the problem is that when I load the data, I have to filter it by id, this is what I should 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 only data with id = 1 to be accepted, but I see 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?

+5
source share
3 answers

You can use the following:

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

instead

 *ngIf="item.id=1" 

You are trying to assign something to the id property (operator = ) instead of checking its value (operator == or === ).

Both ngFor and ngIf are no longer supported on the same element. You can try something like this:

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

Another solution is to create custom pipe filtering:

 import {Pipe} from 'angular2/core'; @Pipe({name: 'filter'}) export class FilterPipe { transform(value, filters) { var filter = function(obj, filters) { return Object.keys(filters).every(prop => obj[prop] === filters[prop]) } return value.filter(obj => filter(obj, filters[0])); } } 

and use it in the component:

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

Custom pipe must be registered on the component:

 @Component({ // ... pipes: [FilterPipe] }) 

Demo: http://plnkr.co/edit/LK5DsaeYnqMdScQw2HGv?p=preview

+6
source

*ngIf and *ngFor on the same tag are not supported. You need to use a long form with an explicit <template> for one of them.

update

Instead of <template> use <ng-container> , which allows you to use the same syntax as inline *ngIf and *ngFor

+3
source

Source: https://habr.com/ru/post/1245686/


All Articles