Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - *ngFor and *ngIf on same element producing error [duplicate]

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.

like image 952
Eesa Avatar asked May 04 '16 11:05

Eesa


1 Answers

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>  
like image 147
Thierry Templier Avatar answered Oct 19 '22 02:10

Thierry Templier