angular - 在 Angular 2 中使用 ngFor 和 ngIf 应用条件

标签 angular typescript

<分区>

您好,我一直在尝试使用 ngIF 和 ngFor 成功过滤数组。

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

这段代码只为类型为 1 的数据显示带有名称的按钮,但它也为每个没有类型 = 1 的数据条目创建空按钮,我不知道如何摆脱空按钮。非常感谢任何帮助。

最佳答案

我会翻转你的 buttondiv :

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

这样只会为有效项目创建按钮。

如果<div>的用途不可取 <ng-container>相反。

虽然出于性能原因不建议使用,但您也可以在组件中使用函数:

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

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

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

虽然这有效,但不推荐,应尽可能避免。

关于angular - 在 Angular 2 中使用 ngFor 和 ngIf 应用条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42931735/

相关文章:

javascript - 无法从其他模块 Angular 找到组件

angular - Angular 谷歌地图上缺少卫星 View 切换

css - 将字体导入 Angular 应用程序

javascript - 将 JQueryUI 与 TypeScript 和 DefinitelyTyped 定义文件一起使用时出错

javascript - Angular Service 提供默认值吗?

angular - 将 css-element-queries 导入到 Angular 6 应用程序

Angular 2 应用程序因 XHR 错误而失败(404 未找到)

angular - 在 Firebase 上托管 Angular 项目

module - 你如何引用 lib.d.ts 类型

angular - 如何修复我的 Angular 测验应用程序中多选题的评分问题?