Angular2 - * ngFor和* ngIf对同一元素产生错误 [英] Angular2 - *ngFor and *ngIf on same element producing error

查看:116
本文介绍了Angular2 - * ngFor和* ngIf对同一元素产生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组用户,我想只在桌面上显示男性用户。以下是我尝试实现此目的的方法:

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

但我收到以下错误:

EXCEPTION:TypeError:无法读取未定义属性'gender'

EXCEPTION: TypeError: Cannot read property 'gender' of undefined

你可以看到我是在同一元素上使用* ngFor和* ngIf,即 tr 。为什么我不能在同一个元素上使用* ngFor和* ngIf?有没有其他方法来实现这一目标?我重新解决了这里有关于探测器的问题,你可以在控制台上看到错误。

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.

推荐答案

实际上,不支持同一元素上的ngIf和ngFor。您可以使用 ngIf 的扩展语法来实现此目的:

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:

UPDATED

<ng-container *ngFor="let user of users">  
<tr *ngIf="user.gender == 'male'">
<td>{{user.name}}</td>
        <td>{{user.gender}}</td>
</tr>
</ng-container>  

这篇关于Angular2 - * ngFor和* ngIf对同一元素产生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆