【发布时间】:2017-10-06 04:41:21
【问题描述】:
我想渲染对象 在某些网格车组件中的可观察数组中。此外,我想将网格卡的数量限制为基于我的组件中的变量的值,即使用*ngIf 条件检查的gridCols*maxRows。
我知道在同一个元素上同时使用*ngFor 和*ngIf 是不可能的。所以我需要使用<template ngFor ...>
包装我的网格卡元素,这些元素将基于*ngFor 有条件地呈现。鉴于此,我如何在*ngIf 中引用*ngFor 中的index 或content 变量。
<template ngFor let-content [ngForOf]="contentObjectsObservable | async" let-i="index" [ngForTrackBy]="trackByFn">
<grid-card *ngIf="i < gridCols*maxRows" [content]="content" [style.width.%]="gridCardWidth"></grid-card>
</template>
更新
我尝试过类似的方法
#i="index"
带有这样的错误信息:
没有将“exportAs”设置为“index”的指令
【问题讨论】:
-
我建议使用切片管道来限制最大行数(或实际上是最大项目数)angular.io/docs/ts/latest/api/common/index/SlicePipe-pipe.html
-
没关系,但我也想知道如何在子元素
中引用 ngFor 循环的索引和内容变量,它也可能有用 -
我不知道
<grid-card>是什么。如果它是您构建的组件,只需添加@Input() index:int; @Input() content:SomeType;之类的输入,然后像<grid-card *ngIf="i < gridCols*maxRows" [index]="i" [content]="content"一样传递它 -
它应该可以工作。
#i="index"已过时,近一年以来不受支持。let-i="index"是正确的形式。您也可以使用<ng-container *ngFor="let content of contentObjectsObservable | async; let i=index">代替<template ...>来使用更常见的语法,但结果相同。 -
尝试通过在
<grid-card前面写{{ i }}来调试它。也可以查看{{gridCols*maxRows}}
标签: angular ngfor angular-ng-if