【问题标题】:Angular: using both *ngFor and *ngIf with reference to index value in child elementsAngular:同时使用 *ngFor 和 *ngIf 并参考子元素中的索引值
【发布时间】:2017-10-06 04:41:21
【问题描述】:

我想渲染对象 在某些网格车组件中的可观察数组中。此外,我想将网格卡的数量限制为基于我的组件中的变量的值,即使用*ngIf 条件检查的gridCols*maxRows

我知道在同一个元素上同时使用*ngFor*ngIf 是不可能的。所以我需要使用<template ngFor ...> 包装我的网格卡元素,这些元素将基于*ngFor 有条件地呈现。鉴于此,我如何在*ngIf 中引用*ngFor 中的indexcontent 变量。

<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 循环的索引和内容变量,它也可能有用
  • 我不知道&lt;grid-card&gt; 是什么。如果它是您构建的组件,只需添加 @Input() index:int; @Input() content:SomeType; 之类的输入,然后像 &lt;grid-card *ngIf="i &lt; gridCols*maxRows" [index]="i" [content]="content" 一样传递它
  • 它应该可以工作。 #i="index" 已过时,近一年以来不受支持。 let-i="index" 是正确的形式。您也可以使用 &lt;ng-container *ngFor="let content of contentObjectsObservable | async; let i=index"&gt; 代替 &lt;template ...&gt; 来使用更常见的语法,但结果相同。
  • 尝试通过在&lt;grid-card前面写{{ i }}来调试它。也可以查看{{gridCols*maxRows}}

标签: angular ngfor angular-ng-if


【解决方案1】:

您可以通过将let i = index 放在*ngFor 语句中来引用*ngFor 的索引! 示例:

<div *ngFor="let item of items; let i = index">
    <div *ngIf="i < (gridCols * maxRows)" class="row">
    <grid-card [content]="content" [style.width.%]="gridCardWidth"></grid-card>
    </div>
</div>

确保您已将 gridCols 和 maxRows 定义为组件中的数字!

gridCols:number = <your number>;
maxRows:number = <your number>;

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2018-07-16
    • 1970-01-01
    • 2019-10-01
    • 2018-06-17
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    相关资源
    最近更新 更多