简体   繁体   English

角度:使用* ngFor和* ngIf引用子元素中的索引值

[英]Angular: using both *ngFor and *ngIf with reference to index value in child elements

I would like to render objects from array observable in some grid-car components. 我想在某些网格车组件中呈现可观察到的数组对象 In addition, I want to limit the number of grid cards to a value based on variables in my component ie gridCols*maxRows using *ngIf condition checking. 另外,我想根据组件中的变量(即使用*ngIf条件检查的gridCols*maxRows将网格卡的数量限制为一个值。

I know that it is not possible to use both *ngFor and *ngIf simultaneously on the same element. 我知道不可能在同一元素上同时使用*ngFor*ngIf So I need to use <template ngFor ...> to wrap my grid-card elements which will be conditionally rendered based on *ngFor . 所以我需要使用<template ngFor ...>包装我的网格卡元素,这些元素将根据*ngFor有条件地呈现。 Given this, how I can reference index or content variables from *ngFor in *ngIf . 鉴于此,我如何从*ngFor中的*ngIf引用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> 

UPDATE 更新

I have tried something like this 我已经尝试过这样的事情

 #i="index"

with such error message: 与这样的错误信息:

There is no directive with "exportAs" set to "index" 没有将“ exportAs”设置为“ index”的指令

You can reference the index from *ngFor by putting let i = index in the *ngFor statement! 您可以通过将let i = index放在* ngFor语句中来从* ngFor引用索引! Example: 例:

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

Make sure that you have defined gridCols and maxRows as numbers in your component! 确保已在组件中将gridCols和maxRows定义为数字!

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

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM