在angular 2中使用ngFor和ngIf施加条件 [英] Apply a condition using ngFor and ngIf in angular 2

查看:565
本文介绍了在angular 2中使用ngFor和ngIf施加条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用ngIF和ngFor筛选成功的数组.

Hi There I have been trying to filter an array with some success using ngIF and ngFor.

<button *ngFor="let item of items"> <div *ngIf="(item.data.type == 1)"> {{item.data.name}} </div> </button>

此代码仅显示具有类型= 1的数据的带有名称的按钮,但是它还会为每个没有类型= 1的数据条目创建空按钮,我不知道如何摆脱空按钮.非常感谢您的帮助.

This code does only show buttons with name in it for data that has type=1 but it also create empty buttons for each data entry that doesn't have type=1, I can't figure out how to get rid of empty buttons. Any help is much appreciated.

推荐答案

我会翻转您的buttondiv:

<div *ngFor="let item of items">
    <button *ngIf="(item.data.type == 1)">{{item.data.name}}</button>
</div>

通过这种方式,只会为有效项目创建按钮.

This way only buttons get created for valid items.

您还可以在组件中使用一个函数:

You can also use a function in your component:

<button *ngFor="let item of filterItemsOfType('1')">{{item.data.name}}</button>

您的组件具有功能的地方:

Where your component has a function:

filterItemsOfType(type){
    return this.items.filter(x => x.data.type == type);
}

这篇关于在angular 2中使用ngFor和ngIf施加条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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