I have an array of users and I want to show only male users on the table. Here is how I am trying to achieve this:
import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
@Component({
selector: 'app',
template:`
<table>
<tbody>
<tr *ngFor="#user of users" *ngIf="user.gender == 'male' " >
<td>{{user.name}}</td>
<td>{{user.gender}}</td>
</tr>
</tbody>
</table>
`
})
export class AppCmp{
public users = [
{
name: "Eesa",
gender: "male"
},
{
name: "Abdullah",
gender: "male"
},
{
name: "Javeria",
gender: "female"
}
]
}
bootstrap(AppCmp);
but I am getting the following error:
EXCEPTION: TypeError: Cannot read property 'gender' of undefined
as you can see I am using *ngFor and *ngIf on the same element i.e. tr
. Why can't I use *ngFor and *ngIf on the same element? Is there any other way of achieving this? I re-produced the problem here on plunker you can see the error on the console.
In fact, ngIf and ngFor on a same element isn't supported. You could use the expanded syntax of ngIf
to be able to implement this:
Initial version:
<tr *ngFor="#user of users">
<template [ngIf]="user.gender == 'male'">
<td>{{user.name}}</td>
<td>{{user.gender}}</td>
</template>
</tr>
Updated version with latest Angular selectors.
<ng-container *ngFor="let user of users">
<tr *ngIf="user.gender == 'male'">
<td>{{user.name}}</td>
<td>{{user.gender}}</td>
</tr>
</ng-container>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With