首页 文章

Angular 2 - * ngFor:有没有办法使用替代结束条件?

提问于
浏览
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的结束条件 .

非常感谢您的帮助!

2 回答

  • 2

    *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

  • 1

    我终于解决了我的问题一个丑陋而又有效的方法......我没有编写另一个结束条件,而是使用由函数计算的长度数组进行循环 . 我在那个循环中读了我的另一个数组(带有我的照片的那个) .

    Angular应该为此做点什么!谢谢你的帮助!

    如何解决它的示例:

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

相关问题