2016-08-01 75 views
2

我来这里是因为经过很多小时的搜索后,我没有找到一种方法来使用内置指令制作的循环的替代停止条件:* ngFor。Angular 2 - * ngFor:有没有办法使用替代停止条件?

其实任何* ngFor完成循环的条件:index < array.length。我想知道是否有办法用另一个条件完成循环:i < myVariable

如果你想知道为什么我想这样做,是因为我工作的一个图片库工作这种方式:

<div *ngFor="let pic of pics; let i = index"> 
    <div *ngIf="whichRowType(i) == 3"> 
     <small>pic[whichIndex(i)].id</small> 
     <small>pic[currentIndex + 1].id</small> 
     <small>pic[currentIndex + 2].id</small> 
    </div> 

    <div *ngIf="whichRowType(i) == 2"> 
     <small>pic[whichIndex(i)].id</small> 
     <small>pic[currentIndex + 1].id</small> 
    </div> 

    <div *ngIf="whichRowType(i) == 1"> 
     <small>pic[whichIndex(i)].id</small> 
    </div> 
</div> 

在这个例子中,我创建了一个排各3张照片。我有三种类型的行: - 显示一张图片, - 显示两张图片, - 显示三张图片。

问题是,我的第一张图片在每一行上的索引总是低于用于显示该行的索引。所以如果我想能够显示我所有的图片,我必须能够在我的* ngFor上更改我的停止条件。

非常感谢您的帮助!

+0

只是揭露你到其他的生态系统:如果您使用JSX你就不会对此有任何的困惑(因为它只是JavaScript的),并与打字稿很好的支持: https://www.youtube.com/watch?v=-oEa6UueHsk – basarat

+0

希望这可能有助于替代[循环休息](https://stackoverflow.com/questions/39911219/break-ngfor-loop-in -angualr2/44313643#44313643) – KCP

+0

感谢你们两位的帮助! ;) –

回答

1

我终于解决了我的问题,一个丑陋,但工作方式...... 而不是写我确实同一个循环另一端条件一个由函数计算的长度数组。我在那个循环中读了我的另一个数组(我的图片)。

Angular应该真的为此做些什么! 谢谢你们的帮助,我真的很感激!

的如何解决这个问题举例:

<div *ngFor="let galleryIndex of galleryIndexes; let i = index"> 
    <div *ngIf="whichRowType(galleryIndex) == 3"> 
     <small>pics[whichIndex(galleryIndex)].id</small> 
     <small>pics[currentIndex + 1].id</small> 
     <small>pics[currentIndex + 2].id</small> 
    </div> 

    <div *ngIf="whichRowType(galleryIndex) == 2"> 
     <small>pics[whichIndex(galleryIndex)].id</small> 
     <small>pics[currentIndex + 1].id</small> 
    </div> 

    <div *ngIf="whichRowType(galleryIndex) == 1"> 
     <small>pics[whichIndex(galleryIndex)].id</small> 
    </div> 
</div> 
+0

也许你只是想使用切片管道https://angular.io/docs/ts/latest/guide/pipes.html –

1

*ngFor提供last值:

<div *ngFor="let pic of pics; let i = index; let last=last"> 
    <div *ngIf="last"> 
     ... 
    </div> 
    </div> 

又见Implementing ngClassEven ngClassOdd for angular 2

+0

嗨! 非常感谢您的快速回复,但这不是我要找的。正如你可以在angular2文档中看到的:“last将被设置为一个布尔值,指示该项是否是迭代中的最后一个。” 我不需要检测当我在最后一个索引时,我必须允许我的循环在最后一个索引后继续。 –

+0

不知道你是什么意思与停止条件。 –

+0

我的意思是说,ngFor是一个循环,当索引优于array.length时会停止。当索引优于我班的变量时,我需要停止循环。 –

相关问题